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

figs.html 114 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
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
  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">from copy import deepcopy
  25. from typing import List
  26. import matplotlib.pyplot as plt
  27. import numpy as np
  28. import pandas as pd
  29. from scipy.special import expit
  30. from sklearn import datasets
  31. from sklearn import tree
  32. from sklearn.base import BaseEstimator, ClassifierMixin, RegressorMixin
  33. from sklearn.model_selection import train_test_split, cross_val_score
  34. from sklearn.tree import plot_tree, DecisionTreeClassifier
  35. from sklearn.utils import check_X_y, check_array
  36. from sklearn.utils.validation import _check_sample_weight, check_is_fitted
  37. from imodels.tree.viz_utils import extract_sklearn_tree_from_figs
  38. from imodels.util.arguments import check_fit_arguments
  39. from imodels.util.data_util import encode_categories
  40. class Node:
  41. def __init__(
  42. self,
  43. feature: int = None,
  44. threshold: int = None,
  45. value=None,
  46. value_sklearn=None,
  47. idxs=None,
  48. is_root: bool = False,
  49. left=None,
  50. impurity: float = None,
  51. impurity_reduction: float = None,
  52. tree_num: int = None,
  53. node_id: int = None,
  54. right=None,
  55. ):
  56. &#34;&#34;&#34;Node class for splitting&#34;&#34;&#34;
  57. # split or linear
  58. self.is_root = is_root
  59. self.idxs = idxs
  60. self.tree_num = tree_num
  61. self.node_id = None
  62. self.feature = feature
  63. self.impurity = impurity
  64. self.impurity_reduction = impurity_reduction
  65. self.value_sklearn = value_sklearn
  66. # different meanings
  67. self.value = value # for split this is mean, for linear this is weight
  68. # split-specific
  69. self.threshold = threshold
  70. self.left = left
  71. self.right = right
  72. self.left_temp = None
  73. self.right_temp = None
  74. def setattrs(self, **kwargs):
  75. for k, v in kwargs.items():
  76. setattr(self, k, v)
  77. def __str__(self):
  78. if self.is_root:
  79. return f&#34;X_{self.feature} &lt;= {self.threshold:0.3f} (Tree #{self.tree_num} root)&#34;
  80. elif self.left is None and self.right is None:
  81. return f&#34;Val: {self.value[0][0]:0.3f} (leaf)&#34;
  82. else:
  83. return f&#34;X_{self.feature} &lt;= {self.threshold:0.3f} (split)&#34;
  84. def print_root(self, y):
  85. try:
  86. one_count = pd.Series(y).value_counts()[1.0]
  87. except KeyError:
  88. one_count = 0
  89. one_proportion = (
  90. f&#34; {one_count}/{y.shape[0]} ({round(100 * one_count / y.shape[0], 2)}%)&#34;
  91. )
  92. if self.is_root:
  93. return f&#34;X_{self.feature} &lt;= {self.threshold:0.3f}&#34; + one_proportion
  94. elif self.left is None and self.right is None:
  95. return f&#34;ΔRisk = {self.value[0][0]:0.2f}&#34; + one_proportion
  96. else:
  97. return f&#34;X_{self.feature} &lt;= {self.threshold:0.3f}&#34; + one_proportion
  98. def __repr__(self):
  99. return self.__str__()
  100. class FIGS(BaseEstimator):
  101. &#34;&#34;&#34;FIGS (sum of trees) classifier.
  102. Fast Interpretable Greedy-Tree Sums (FIGS) is an algorithm for fitting concise rule-based models.
  103. Specifically, FIGS generalizes CART to simultaneously grow a flexible number of trees in a summation.
  104. The total number of splits across all the trees can be restricted by a pre-specified threshold, keeping the model interpretable.
  105. Experiments across real-world datasets show that FIGS achieves state-of-the-art prediction performance when restricted to just a few splits (e.g. less than 20).
  106. https://arxiv.org/abs/2201.11931
  107. &#34;&#34;&#34;
  108. def __init__(
  109. self,
  110. max_rules: int = 12,
  111. max_trees: int = None,
  112. min_impurity_decrease: float = 0.0,
  113. random_state=None,
  114. max_features: str = None,
  115. ):
  116. &#34;&#34;&#34;
  117. Params
  118. ------
  119. max_rules: int
  120. Max total number of rules across all trees
  121. max_trees: int
  122. Max total number of trees
  123. min_impurity_decrease: float
  124. A node will be split if this split induces a decrease of the impurity greater than or equal to this value.
  125. max_features
  126. The number of features to consider when looking for the best split (see https://scikit-learn.org/stable/modules/generated/sklearn.ensemble.RandomForestClassifier.html)
  127. &#34;&#34;&#34;
  128. super().__init__()
  129. self.max_rules = max_rules
  130. self.max_trees = max_trees
  131. self.min_impurity_decrease = min_impurity_decrease
  132. self.random_state = random_state
  133. self.max_features = max_features
  134. self._init_decision_function()
  135. def _init_decision_function(self):
  136. &#34;&#34;&#34;Sets decision function based on _estimator_type&#34;&#34;&#34;
  137. # used by sklearn GridSearchCV, BaggingClassifier
  138. if isinstance(self, ClassifierMixin):
  139. def decision_function(x):
  140. return self.predict_proba(x)[:, 1]
  141. elif isinstance(self, RegressorMixin):
  142. decision_function = self.predict
  143. def _construct_node_with_stump(
  144. self,
  145. X,
  146. y,
  147. idxs,
  148. tree_num,
  149. sample_weight=None,
  150. compare_nodes_with_sample_weight=True,
  151. max_features=None,
  152. ):
  153. &#34;&#34;&#34;
  154. Params
  155. ------
  156. compare_nodes_with_sample_weight: Deprecated
  157. If this is set to true and sample_weight is passed, use sample_weight to compare nodes
  158. Otherwise, use sample_weight only for picking a split given a particular node
  159. &#34;&#34;&#34;
  160. # array indices
  161. SPLIT = 0
  162. LEFT = 1
  163. RIGHT = 2
  164. # fit stump
  165. stump = tree.DecisionTreeRegressor(max_depth=1, max_features=max_features)
  166. sweight = None
  167. if sample_weight is not None:
  168. sweight = sample_weight[idxs]
  169. stump.fit(X[idxs], y[idxs], sample_weight=sweight)
  170. # these are all arrays, arr[0] is split node
  171. # note: -2 is dummy
  172. feature = stump.tree_.feature
  173. threshold = stump.tree_.threshold
  174. impurity = stump.tree_.impurity
  175. n_node_samples = stump.tree_.n_node_samples
  176. value = stump.tree_.value
  177. # no split
  178. if len(feature) == 1:
  179. # print(&#39;no split found!&#39;, idxs.sum(), impurity, feature)
  180. return Node(
  181. idxs=idxs,
  182. value=value[SPLIT],
  183. tree_num=tree_num,
  184. feature=feature[SPLIT],
  185. threshold=threshold[SPLIT],
  186. impurity=impurity[SPLIT],
  187. impurity_reduction=None,
  188. )
  189. # manage sample weights
  190. idxs_split = X[:, feature[SPLIT]] &lt;= threshold[SPLIT]
  191. idxs_left = idxs_split &amp; idxs
  192. idxs_right = ~idxs_split &amp; idxs
  193. if sample_weight is None:
  194. n_node_samples_left = n_node_samples[LEFT]
  195. n_node_samples_right = n_node_samples[RIGHT]
  196. else:
  197. n_node_samples_left = sample_weight[idxs_left].sum()
  198. n_node_samples_right = sample_weight[idxs_right].sum()
  199. n_node_samples_split = n_node_samples_left + n_node_samples_right
  200. # calculate impurity
  201. impurity_reduction = (
  202. impurity[SPLIT]
  203. - impurity[LEFT] * n_node_samples_left / n_node_samples_split
  204. - impurity[RIGHT] * n_node_samples_right / n_node_samples_split
  205. ) * n_node_samples_split
  206. node_split = Node(
  207. idxs=idxs,
  208. value=value[SPLIT],
  209. tree_num=tree_num,
  210. feature=feature[SPLIT],
  211. threshold=threshold[SPLIT],
  212. impurity=impurity[SPLIT],
  213. impurity_reduction=impurity_reduction,
  214. )
  215. # print(&#39;\t&gt;&gt;&gt;&#39;, node_split, &#39;impurity&#39;, impurity, &#39;num_pts&#39;, idxs.sum(), &#39;imp_reduc&#39;, impurity_reduction)
  216. # manage children
  217. node_left = Node(
  218. idxs=idxs_left,
  219. value=value[LEFT],
  220. impurity=impurity[LEFT],
  221. tree_num=tree_num,
  222. )
  223. node_right = Node(
  224. idxs=idxs_right,
  225. value=value[RIGHT],
  226. impurity=impurity[RIGHT],
  227. tree_num=tree_num,
  228. )
  229. node_split.setattrs(
  230. left_temp=node_left,
  231. right_temp=node_right,
  232. )
  233. return node_split
  234. def _encode_categories(self, X, categorical_features):
  235. encoder = None
  236. if hasattr(self, &#34;_encoder&#34;):
  237. encoder = self._encoder
  238. return encode_categories(X, categorical_features, encoder)
  239. def fit(
  240. self,
  241. X,
  242. y=None,
  243. feature_names=None,
  244. verbose=False,
  245. sample_weight=None,
  246. categorical_features=None,
  247. ):
  248. &#34;&#34;&#34;
  249. Params
  250. ------
  251. _sample_weight: array-like of shape (n_samples,), default=None
  252. Sample weights. If None, then samples are equally weighted.
  253. Splits that would create child nodes with net zero or negative weight
  254. are ignored while searching for a split in each node.
  255. &#34;&#34;&#34;
  256. if categorical_features is not None:
  257. X, self._encoder = self._encode_categories(X, categorical_features)
  258. X, y, feature_names = check_fit_arguments(self, X, y, feature_names)
  259. if sample_weight is not None:
  260. sample_weight = _check_sample_weight(sample_weight, X)
  261. self.trees_ = [] # list of the root nodes of added trees
  262. self.complexity_ = 0 # tracks the number of rules in the model
  263. y_predictions_per_tree = {} # predictions for each tree
  264. y_residuals_per_tree = {} # based on predictions above
  265. # set up initial potential_splits
  266. # everything in potential_splits either is_root (so it can be added directly to self.trees_)
  267. # or it is a child of a root node that has already been added
  268. idxs = np.ones(X.shape[0], dtype=bool)
  269. node_init = self._construct_node_with_stump(
  270. X=X,
  271. y=y,
  272. idxs=idxs,
  273. tree_num=-1,
  274. sample_weight=sample_weight,
  275. max_features=self.max_features,
  276. )
  277. potential_splits = [node_init]
  278. for node in potential_splits:
  279. node.setattrs(is_root=True)
  280. potential_splits = sorted(potential_splits, key=lambda x: x.impurity_reduction)
  281. # start the greedy fitting algorithm
  282. finished = False
  283. while len(potential_splits) &gt; 0 and not finished:
  284. # print(&#39;potential_splits&#39;, [str(s) for s in potential_splits])
  285. # get node with max impurity_reduction (since it&#39;s sorted)
  286. split_node = potential_splits.pop()
  287. # don&#39;t split on node
  288. if split_node.impurity_reduction &lt; self.min_impurity_decrease:
  289. finished = True
  290. break
  291. elif (
  292. split_node.is_root
  293. and self.max_trees is not None
  294. and len(self.trees_) &gt;= self.max_trees
  295. ):
  296. # If the node is the root of a new tree and we have reached self.max_trees,
  297. # don&#39;t split on it, but allow later splits to continue growing existing trees
  298. continue
  299. # split on node
  300. if verbose:
  301. print(&#34;\nadding &#34; + str(split_node))
  302. self.complexity_ += 1
  303. # if added a tree root
  304. if split_node.is_root:
  305. # start a new tree
  306. self.trees_.append(split_node)
  307. # update tree_num
  308. for node_ in [split_node, split_node.left_temp, split_node.right_temp]:
  309. if node_ is not None:
  310. node_.tree_num = len(self.trees_) - 1
  311. # add new root potential node
  312. node_new_root = Node(
  313. is_root=True, idxs=np.ones(X.shape[0], dtype=bool), tree_num=-1
  314. )
  315. potential_splits.append(node_new_root)
  316. # add children to potential splits
  317. # assign left_temp, right_temp to be proper children
  318. # (basically adds them to tree in predict method)
  319. split_node.setattrs(left=split_node.left_temp, right=split_node.right_temp)
  320. # add children to potential_splits
  321. potential_splits.append(split_node.left)
  322. potential_splits.append(split_node.right)
  323. # update predictions for altered tree
  324. for tree_num_ in range(len(self.trees_)):
  325. y_predictions_per_tree[tree_num_] = self._predict_tree(
  326. self.trees_[tree_num_], X
  327. )
  328. # dummy 0 preds for possible new trees
  329. y_predictions_per_tree[-1] = np.zeros(X.shape[0])
  330. # update residuals for each tree
  331. # -1 is key for potential new tree
  332. for tree_num_ in list(range(len(self.trees_))) + [-1]:
  333. y_residuals_per_tree[tree_num_] = deepcopy(y)
  334. # subtract predictions of all other trees
  335. # Since the current tree makes a constant prediction over the node being split,
  336. # one may ignore its contributions to the residuals without affecting the impurity decrease.
  337. for tree_num_other_ in range(len(self.trees_)):
  338. if not tree_num_other_ == tree_num_:
  339. y_residuals_per_tree[tree_num_] -= y_predictions_per_tree[
  340. tree_num_other_
  341. ]
  342. # recompute all impurities + update potential_split children
  343. potential_splits_new = []
  344. for potential_split in potential_splits:
  345. y_target = y_residuals_per_tree[potential_split.tree_num]
  346. # re-calculate the best split
  347. potential_split_updated = self._construct_node_with_stump(
  348. X=X,
  349. y=y_target,
  350. idxs=potential_split.idxs,
  351. tree_num=potential_split.tree_num,
  352. sample_weight=sample_weight,
  353. max_features=self.max_features,
  354. )
  355. # need to preserve certain attributes from before (value at this split + is_root)
  356. # value may change because residuals may have changed, but we want it to store the value from before
  357. potential_split.setattrs(
  358. feature=potential_split_updated.feature,
  359. threshold=potential_split_updated.threshold,
  360. impurity_reduction=potential_split_updated.impurity_reduction,
  361. impurity=potential_split_updated.impurity,
  362. left_temp=potential_split_updated.left_temp,
  363. right_temp=potential_split_updated.right_temp,
  364. )
  365. # this is a valid split
  366. if potential_split.impurity_reduction is not None:
  367. potential_splits_new.append(potential_split)
  368. # sort so largest impurity reduction comes last (should probs make this a heap later)
  369. potential_splits = sorted(
  370. potential_splits_new, key=lambda x: x.impurity_reduction
  371. )
  372. if verbose:
  373. print(self)
  374. if self.max_rules is not None and self.complexity_ &gt;= self.max_rules:
  375. finished = True
  376. break
  377. # annotate final tree with node_id and value_sklearn, and prepare importance_data_
  378. importance_data = []
  379. for tree_ in self.trees_:
  380. node_counter = iter(range(0, int(1e06)))
  381. def _annotate_node(node: Node, X, y):
  382. if node is None:
  383. return
  384. # TODO does not incorporate sample weights
  385. value_counts = pd.Series(y).value_counts()
  386. try:
  387. neg_count = value_counts[0.0]
  388. except KeyError:
  389. neg_count = 0
  390. try:
  391. pos_count = value_counts[1.0]
  392. except KeyError:
  393. pos_count = 0
  394. value_sklearn = np.array([neg_count, pos_count], dtype=float)
  395. node.setattrs(node_id=next(node_counter), value_sklearn=value_sklearn)
  396. idxs_left = X[:, node.feature] &lt;= node.threshold
  397. _annotate_node(node.left, X[idxs_left], y[idxs_left])
  398. _annotate_node(node.right, X[~idxs_left], y[~idxs_left])
  399. _annotate_node(tree_, X, y)
  400. # now that the samples per node are known, we can start to compute the importances
  401. importance_data_tree = np.zeros(len(self.feature_names_))
  402. def _importances(node: Node):
  403. if node is None or node.left is None:
  404. return 0.0
  405. # TODO does not incorporate sample weights, but will if added to value_sklearn
  406. importance_data_tree[node.feature] += (
  407. np.sum(node.value_sklearn) * node.impurity
  408. - np.sum(node.left.value_sklearn) * node.left.impurity
  409. - np.sum(node.right.value_sklearn) * node.right.impurity
  410. )
  411. return (
  412. np.sum(node.value_sklearn)
  413. + _importances(node.left)
  414. + _importances(node.right)
  415. )
  416. # require the tree to have more than 1 node, otherwise just leave importance_data_tree as zeros
  417. if 1 &lt; next(node_counter):
  418. tree_samples = _importances(tree_)
  419. if tree_samples != 0:
  420. importance_data_tree /= tree_samples
  421. else:
  422. importance_data_tree = 0
  423. importance_data.append(importance_data_tree)
  424. self.importance_data_ = importance_data
  425. return self
  426. def _tree_to_str(self, root: Node, prefix=&#34;&#34;):
  427. if root is None:
  428. return &#34;&#34;
  429. elif root.threshold is None:
  430. return &#34;&#34;
  431. pprefix = prefix + &#34;\t&#34;
  432. return (
  433. prefix
  434. + str(root)
  435. + &#34;\n&#34;
  436. + self._tree_to_str(root.left, pprefix)
  437. + self._tree_to_str(root.right, pprefix)
  438. )
  439. def _tree_to_str_with_data(self, X, y, root: Node, prefix=&#34;&#34;):
  440. if root is None:
  441. return &#34;&#34;
  442. elif root.threshold is None:
  443. return &#34;&#34;
  444. pprefix = prefix + &#34;\t&#34;
  445. left = X[:, root.feature] &lt;= root.threshold
  446. return (
  447. prefix
  448. + root.print_root(y)
  449. + &#34;\n&#34;
  450. + self._tree_to_str_with_data(X[left], y[left], root.left, pprefix)
  451. + self._tree_to_str_with_data(X[~left], y[~left], root.right, pprefix)
  452. )
  453. def __str__(self):
  454. if not hasattr(self, &#34;trees_&#34;):
  455. s = self.__class__.__name__
  456. s += &#34;(&#34;
  457. s += &#34;max_rules=&#34;
  458. s += repr(self.max_rules)
  459. s += &#34;)&#34;
  460. return s
  461. else:
  462. s = &#34;&gt; ------------------------------\n&#34;
  463. s += &#34;&gt; FIGS-Fast Interpretable Greedy-Tree Sums:\n&#34;
  464. s += &#39;&gt; \tPredictions are made by summing the &#34;Val&#34; reached by traversing each tree.\n&#39;
  465. s += &#34;&gt; \tFor classifiers, a sigmoid function is then applied to the sum.\n&#34;
  466. s += &#34;&gt; ------------------------------\n&#34;
  467. s += &#34;\n\t+\n&#34;.join([self._tree_to_str(t) for t in self.trees_])
  468. if hasattr(self, &#34;feature_names_&#34;) and self.feature_names_ is not None:
  469. for i in range(len(self.feature_names_))[::-1]:
  470. s = s.replace(f&#34;X_{i}&#34;, self.feature_names_[i])
  471. return s
  472. def print_tree(self, X, y, feature_names=None):
  473. s = &#34;------------\n&#34; + &#34;\n\t+\n&#34;.join(
  474. [self._tree_to_str_with_data(X, y, t) for t in self.trees_]
  475. )
  476. if feature_names is None:
  477. if hasattr(self, &#34;feature_names_&#34;) and self.feature_names_ is not None:
  478. feature_names = self.feature_names_
  479. if feature_names is not None:
  480. for i in range(len(feature_names))[::-1]:
  481. s = s.replace(f&#34;X_{i}&#34;, feature_names[i])
  482. return s
  483. def predict(self, X, categorical_features=None):
  484. if hasattr(self, &#34;_encoder&#34;):
  485. X = self._encode_categories(X, categorical_features=categorical_features)
  486. X = check_array(X)
  487. preds = np.zeros(X.shape[0])
  488. for tree in self.trees_:
  489. preds += self._predict_tree(tree, X)
  490. if isinstance(self, RegressorMixin):
  491. return preds
  492. elif isinstance(self, ClassifierMixin):
  493. return (preds &gt; 0.5).astype(int)
  494. def predict_proba(self, X, categorical_features=None, use_clipped_prediction=False):
  495. &#34;&#34;&#34;Predict probability for classifiers:
  496. Default behavior is to constrain the outputs to the range of probabilities, i.e. 0 to 1, with a sigmoid function.
  497. Set use_clipped_prediction=True to use prior behavior of clipping between 0 and 1 instead.
  498. &#34;&#34;&#34;
  499. if hasattr(self, &#34;_encoder&#34;):
  500. X = self._encode_categories(X, categorical_features=categorical_features)
  501. X = check_array(X)
  502. if isinstance(self, RegressorMixin):
  503. return NotImplemented
  504. preds = np.zeros(X.shape[0])
  505. for tree in self.trees_:
  506. preds += self._predict_tree(tree, X)
  507. if use_clipped_prediction:
  508. # old behavior, pre v1.3.9
  509. # constrain to range of probabilities by clipping
  510. preds = np.clip(preds, a_min=0.0, a_max=1.0)
  511. else:
  512. # constrain to range of probabilities with a sigmoid function
  513. preds = expit(preds)
  514. return np.vstack((1 - preds, preds)).transpose()
  515. def _predict_tree(self, root: Node, X):
  516. &#34;&#34;&#34;Predict for a single tree&#34;&#34;&#34;
  517. def _predict_tree_single_point(root: Node, x):
  518. if root.left is None and root.right is None:
  519. return root.value[0, 0]
  520. left = x[root.feature] &lt;= root.threshold
  521. if left:
  522. if root.left is None: # we don&#39;t actually have to worry about this case
  523. return root.value
  524. else:
  525. return _predict_tree_single_point(root.left, x)
  526. else:
  527. if (
  528. root.right is None
  529. ): # we don&#39;t actually have to worry about this case
  530. return root.value
  531. else:
  532. return _predict_tree_single_point(root.right, x)
  533. preds = np.zeros(X.shape[0])
  534. for i in range(X.shape[0]):
  535. preds[i] = _predict_tree_single_point(root, X[i])
  536. return preds
  537. @property
  538. def feature_importances_(self):
  539. &#34;&#34;&#34;Gini impurity-based feature importances&#34;&#34;&#34;
  540. check_is_fitted(self)
  541. avg_feature_importances = np.mean(
  542. self.importance_data_, axis=0, dtype=np.float64
  543. )
  544. return avg_feature_importances / np.sum(avg_feature_importances)
  545. def plot(
  546. self,
  547. cols=2,
  548. feature_names=None,
  549. filename=None,
  550. label=&#34;all&#34;,
  551. impurity=False,
  552. tree_number=None,
  553. dpi=150,
  554. fig_size=None,
  555. ):
  556. is_single_tree = len(self.trees_) &lt; 2 or tree_number is not None
  557. n_cols = int(cols)
  558. n_rows = int(np.ceil(len(self.trees_) / n_cols))
  559. if feature_names is None:
  560. if hasattr(self, &#34;feature_names_&#34;) and self.feature_names_ is not None:
  561. feature_names = self.feature_names_
  562. n_plots = int(len(self.trees_)) if tree_number is None else 1
  563. fig, axs = plt.subplots(n_plots, dpi=dpi)
  564. if fig_size is not None:
  565. fig.set_size_inches(fig_size, fig_size)
  566. n_classes = 1 if isinstance(self, RegressorMixin) else 2
  567. ax_size = int(len(self.trees_))
  568. for i in range(n_plots):
  569. r = i // n_cols
  570. c = i % n_cols
  571. if not is_single_tree:
  572. ax = axs[i]
  573. else:
  574. ax = axs
  575. try:
  576. dt = extract_sklearn_tree_from_figs(
  577. self, i if tree_number is None else tree_number, n_classes
  578. )
  579. plot_tree(
  580. dt,
  581. ax=ax,
  582. feature_names=feature_names,
  583. label=label,
  584. impurity=impurity,
  585. )
  586. except IndexError:
  587. ax.axis(&#34;off&#34;)
  588. continue
  589. ttl = f&#34;Tree {i}&#34; if n_plots &gt; 1 else f&#34;Tree {tree_number}&#34;
  590. ax.set_title(ttl)
  591. if filename is not None:
  592. plt.savefig(filename)
  593. return
  594. plt.show()
  595. class FIGSRegressor(FIGS, RegressorMixin):
  596. ...
  597. class FIGSClassifier(FIGS, ClassifierMixin):
  598. ...
  599. class FIGSCV:
  600. def __init__(
  601. self,
  602. figs,
  603. n_rules_list: List[int] = [6, 12, 24, 30, 50],
  604. n_trees_list: List[int] = [5, 5, 5, 5, 5],
  605. cv: int = 3,
  606. scoring=None,
  607. *args,
  608. **kwargs,
  609. ):
  610. if len(n_rules_list) != len(n_trees_list):
  611. raise ValueError(
  612. f&#34;len(n_rules_list) = {len(n_rules_list)} != len(n_trees_list) = {len(n_trees_list)}&#34;
  613. )
  614. self._figs_class = figs
  615. self.n_rules_list = np.array(n_rules_list)
  616. self.n_trees_list = np.array(n_trees_list)
  617. self.cv = cv
  618. self.scoring = scoring
  619. def fit(self, X, y):
  620. self.scores_ = []
  621. for _i, n_rules in enumerate(self.n_rules_list):
  622. est = self._figs_class(max_rules=n_rules, max_trees=self.n_trees_list[_i])
  623. cv_scores = cross_val_score(est, X, y, cv=self.cv, scoring=self.scoring)
  624. mean_score = np.mean(cv_scores)
  625. if len(self.scores_) == 0:
  626. self.figs = est
  627. elif mean_score &gt; np.max(self.scores_):
  628. self.figs = est
  629. self.scores_.append(mean_score)
  630. self.figs.fit(X=X, y=y)
  631. def predict_proba(self, X):
  632. return self.figs.predict_proba(X)
  633. def predict(self, X):
  634. return self.figs.predict(X)
  635. @property
  636. def max_rules(self):
  637. return self.figs.max_rules
  638. @property
  639. def max_trees(self):
  640. return self.figs.max_trees
  641. class FIGSRegressorCV(FIGSCV):
  642. def __init__(
  643. self,
  644. n_rules_list: List[int] = [6, 12, 24, 30, 50],
  645. n_trees_list: List[int] = [5, 5, 5, 5, 5],
  646. cv: int = 3,
  647. scoring=&#34;r2&#34;,
  648. *args,
  649. **kwargs,
  650. ):
  651. super(FIGSRegressorCV, self).__init__(
  652. figs=FIGSRegressor,
  653. n_rules_list=n_rules_list,
  654. n_trees_list=n_trees_list,
  655. cv=cv,
  656. scoring=scoring,
  657. *args,
  658. **kwargs,
  659. )
  660. class FIGSClassifierCV(FIGSCV):
  661. def __init__(
  662. self,
  663. n_rules_list: List[int] = [6, 12, 24, 30, 50],
  664. n_trees_list: List[int] = [5, 5, 5, 5, 5],
  665. cv: int = 3,
  666. scoring=&#34;accuracy&#34;,
  667. *args,
  668. **kwargs,
  669. ):
  670. super(FIGSClassifierCV, self).__init__(
  671. figs=FIGSClassifier,
  672. n_rules_list=n_rules_list,
  673. n_trees_list=n_trees_list,
  674. cv=cv,
  675. scoring=scoring,
  676. *args,
  677. **kwargs,
  678. )
  679. if __name__ == &#34;__main__&#34;:
  680. from sklearn import datasets
  681. X_cls, Y_cls = datasets.load_breast_cancer(return_X_y=True)
  682. X_reg, Y_reg = datasets.make_friedman1(100)
  683. categories = [&#34;cat&#34;, &#34;dog&#34;, &#34;bird&#34;, &#34;fish&#34;]
  684. categories_2 = [&#34;bear&#34;, &#34;chicken&#34;, &#34;cow&#34;]
  685. X_cat = pd.DataFrame(X_reg)
  686. X_cat[&#34;pet1&#34;] = np.random.choice(categories, size=(100, 1))
  687. X_cat[&#34;pet2&#34;] = np.random.choice(categories_2, size=(100, 1))
  688. # X_cat.columns[-1] = &#34;pet&#34;
  689. Y_cat = Y_reg
  690. est = FIGSRegressor(max_rules=10)
  691. est.fit(X_cat, Y_cat, categorical_features=[&#34;pet1&#34;, &#34;pet2&#34;])
  692. est.predict(X_cat, categorical_features=[&#34;pet1&#34;, &#34;pet2&#34;])
  693. est.plot(tree_number=1)
  694. est = FIGSClassifier(max_rules=10)
  695. # est.fit(X_cls, Y_cls, sample_weight=np.arange(0, X_cls.shape[0]))
  696. est.fit(X_cls, Y_cls, sample_weight=[1] * X_cls.shape[0])
  697. est.predict(X_cls)
  698. est = FIGSRegressorCV()
  699. est.fit(X_reg, Y_reg)
  700. est.predict(X_reg)
  701. print(est.max_rules)
  702. est.figs.plot(tree_number=0)
  703. est = FIGSClassifierCV()
  704. est.fit(X_cls, Y_cls)
  705. est.predict(X_cls)
  706. print(est.max_rules)
  707. est.figs.plot(tree_number=0)
  708. # %%</code></pre>
  709. </details>
  710. </section>
  711. <section>
  712. </section>
  713. <section>
  714. </section>
  715. <section>
  716. </section>
  717. <section>
  718. <h2 class="section-title" id="header-classes">Classes</h2>
  719. <dl>
  720. <dt id="imodels.tree.figs.FIGS"><code class="flex name class">
  721. <span>class <span class="ident">FIGS</span></span>
  722. <span>(</span><span>max_rules: int = 12, max_trees: int = None, min_impurity_decrease: float = 0.0, random_state=None, max_features: str = None)</span>
  723. </code></dt>
  724. <dd>
  725. <div class="desc"><p>FIGS (sum of trees) classifier.
  726. Fast Interpretable Greedy-Tree Sums (FIGS) is an algorithm for fitting concise rule-based models.
  727. Specifically, FIGS generalizes CART to simultaneously grow a flexible number of trees in a summation.
  728. The total number of splits across all the trees can be restricted by a pre-specified threshold, keeping the model interpretable.
  729. Experiments across real-world datasets show that FIGS achieves state-of-the-art prediction performance when restricted to just a few splits (e.g. less than 20).
  730. <a href="https://arxiv.org/abs/2201.11931">https://arxiv.org/abs/2201.11931</a></p>
  731. <h2 id="params">Params</h2>
  732. <p>max_rules: int
  733. Max total number of rules across all trees
  734. max_trees: int
  735. Max total number of trees
  736. min_impurity_decrease: float
  737. A node will be split if this split induces a decrease of the impurity greater than or equal to this value.
  738. max_features
  739. The number of features to consider when looking for the best split (see <a href="https://scikit-learn.org/stable/modules/generated/sklearn.ensemble.RandomForestClassifier.html">https://scikit-learn.org/stable/modules/generated/sklearn.ensemble.RandomForestClassifier.html</a>)</p></div>
  740. <details class="source">
  741. <summary>
  742. <span>Expand source code</span>
  743. </summary>
  744. <pre><code class="python">class FIGS(BaseEstimator):
  745. &#34;&#34;&#34;FIGS (sum of trees) classifier.
  746. Fast Interpretable Greedy-Tree Sums (FIGS) is an algorithm for fitting concise rule-based models.
  747. Specifically, FIGS generalizes CART to simultaneously grow a flexible number of trees in a summation.
  748. The total number of splits across all the trees can be restricted by a pre-specified threshold, keeping the model interpretable.
  749. Experiments across real-world datasets show that FIGS achieves state-of-the-art prediction performance when restricted to just a few splits (e.g. less than 20).
  750. https://arxiv.org/abs/2201.11931
  751. &#34;&#34;&#34;
  752. def __init__(
  753. self,
  754. max_rules: int = 12,
  755. max_trees: int = None,
  756. min_impurity_decrease: float = 0.0,
  757. random_state=None,
  758. max_features: str = None,
  759. ):
  760. &#34;&#34;&#34;
  761. Params
  762. ------
  763. max_rules: int
  764. Max total number of rules across all trees
  765. max_trees: int
  766. Max total number of trees
  767. min_impurity_decrease: float
  768. A node will be split if this split induces a decrease of the impurity greater than or equal to this value.
  769. max_features
  770. The number of features to consider when looking for the best split (see https://scikit-learn.org/stable/modules/generated/sklearn.ensemble.RandomForestClassifier.html)
  771. &#34;&#34;&#34;
  772. super().__init__()
  773. self.max_rules = max_rules
  774. self.max_trees = max_trees
  775. self.min_impurity_decrease = min_impurity_decrease
  776. self.random_state = random_state
  777. self.max_features = max_features
  778. self._init_decision_function()
  779. def _init_decision_function(self):
  780. &#34;&#34;&#34;Sets decision function based on _estimator_type&#34;&#34;&#34;
  781. # used by sklearn GridSearchCV, BaggingClassifier
  782. if isinstance(self, ClassifierMixin):
  783. def decision_function(x):
  784. return self.predict_proba(x)[:, 1]
  785. elif isinstance(self, RegressorMixin):
  786. decision_function = self.predict
  787. def _construct_node_with_stump(
  788. self,
  789. X,
  790. y,
  791. idxs,
  792. tree_num,
  793. sample_weight=None,
  794. compare_nodes_with_sample_weight=True,
  795. max_features=None,
  796. ):
  797. &#34;&#34;&#34;
  798. Params
  799. ------
  800. compare_nodes_with_sample_weight: Deprecated
  801. If this is set to true and sample_weight is passed, use sample_weight to compare nodes
  802. Otherwise, use sample_weight only for picking a split given a particular node
  803. &#34;&#34;&#34;
  804. # array indices
  805. SPLIT = 0
  806. LEFT = 1
  807. RIGHT = 2
  808. # fit stump
  809. stump = tree.DecisionTreeRegressor(max_depth=1, max_features=max_features)
  810. sweight = None
  811. if sample_weight is not None:
  812. sweight = sample_weight[idxs]
  813. stump.fit(X[idxs], y[idxs], sample_weight=sweight)
  814. # these are all arrays, arr[0] is split node
  815. # note: -2 is dummy
  816. feature = stump.tree_.feature
  817. threshold = stump.tree_.threshold
  818. impurity = stump.tree_.impurity
  819. n_node_samples = stump.tree_.n_node_samples
  820. value = stump.tree_.value
  821. # no split
  822. if len(feature) == 1:
  823. # print(&#39;no split found!&#39;, idxs.sum(), impurity, feature)
  824. return Node(
  825. idxs=idxs,
  826. value=value[SPLIT],
  827. tree_num=tree_num,
  828. feature=feature[SPLIT],
  829. threshold=threshold[SPLIT],
  830. impurity=impurity[SPLIT],
  831. impurity_reduction=None,
  832. )
  833. # manage sample weights
  834. idxs_split = X[:, feature[SPLIT]] &lt;= threshold[SPLIT]
  835. idxs_left = idxs_split &amp; idxs
  836. idxs_right = ~idxs_split &amp; idxs
  837. if sample_weight is None:
  838. n_node_samples_left = n_node_samples[LEFT]
  839. n_node_samples_right = n_node_samples[RIGHT]
  840. else:
  841. n_node_samples_left = sample_weight[idxs_left].sum()
  842. n_node_samples_right = sample_weight[idxs_right].sum()
  843. n_node_samples_split = n_node_samples_left + n_node_samples_right
  844. # calculate impurity
  845. impurity_reduction = (
  846. impurity[SPLIT]
  847. - impurity[LEFT] * n_node_samples_left / n_node_samples_split
  848. - impurity[RIGHT] * n_node_samples_right / n_node_samples_split
  849. ) * n_node_samples_split
  850. node_split = Node(
  851. idxs=idxs,
  852. value=value[SPLIT],
  853. tree_num=tree_num,
  854. feature=feature[SPLIT],
  855. threshold=threshold[SPLIT],
  856. impurity=impurity[SPLIT],
  857. impurity_reduction=impurity_reduction,
  858. )
  859. # print(&#39;\t&gt;&gt;&gt;&#39;, node_split, &#39;impurity&#39;, impurity, &#39;num_pts&#39;, idxs.sum(), &#39;imp_reduc&#39;, impurity_reduction)
  860. # manage children
  861. node_left = Node(
  862. idxs=idxs_left,
  863. value=value[LEFT],
  864. impurity=impurity[LEFT],
  865. tree_num=tree_num,
  866. )
  867. node_right = Node(
  868. idxs=idxs_right,
  869. value=value[RIGHT],
  870. impurity=impurity[RIGHT],
  871. tree_num=tree_num,
  872. )
  873. node_split.setattrs(
  874. left_temp=node_left,
  875. right_temp=node_right,
  876. )
  877. return node_split
  878. def _encode_categories(self, X, categorical_features):
  879. encoder = None
  880. if hasattr(self, &#34;_encoder&#34;):
  881. encoder = self._encoder
  882. return encode_categories(X, categorical_features, encoder)
  883. def fit(
  884. self,
  885. X,
  886. y=None,
  887. feature_names=None,
  888. verbose=False,
  889. sample_weight=None,
  890. categorical_features=None,
  891. ):
  892. &#34;&#34;&#34;
  893. Params
  894. ------
  895. _sample_weight: array-like of shape (n_samples,), default=None
  896. Sample weights. If None, then samples are equally weighted.
  897. Splits that would create child nodes with net zero or negative weight
  898. are ignored while searching for a split in each node.
  899. &#34;&#34;&#34;
  900. if categorical_features is not None:
  901. X, self._encoder = self._encode_categories(X, categorical_features)
  902. X, y, feature_names = check_fit_arguments(self, X, y, feature_names)
  903. if sample_weight is not None:
  904. sample_weight = _check_sample_weight(sample_weight, X)
  905. self.trees_ = [] # list of the root nodes of added trees
  906. self.complexity_ = 0 # tracks the number of rules in the model
  907. y_predictions_per_tree = {} # predictions for each tree
  908. y_residuals_per_tree = {} # based on predictions above
  909. # set up initial potential_splits
  910. # everything in potential_splits either is_root (so it can be added directly to self.trees_)
  911. # or it is a child of a root node that has already been added
  912. idxs = np.ones(X.shape[0], dtype=bool)
  913. node_init = self._construct_node_with_stump(
  914. X=X,
  915. y=y,
  916. idxs=idxs,
  917. tree_num=-1,
  918. sample_weight=sample_weight,
  919. max_features=self.max_features,
  920. )
  921. potential_splits = [node_init]
  922. for node in potential_splits:
  923. node.setattrs(is_root=True)
  924. potential_splits = sorted(potential_splits, key=lambda x: x.impurity_reduction)
  925. # start the greedy fitting algorithm
  926. finished = False
  927. while len(potential_splits) &gt; 0 and not finished:
  928. # print(&#39;potential_splits&#39;, [str(s) for s in potential_splits])
  929. # get node with max impurity_reduction (since it&#39;s sorted)
  930. split_node = potential_splits.pop()
  931. # don&#39;t split on node
  932. if split_node.impurity_reduction &lt; self.min_impurity_decrease:
  933. finished = True
  934. break
  935. elif (
  936. split_node.is_root
  937. and self.max_trees is not None
  938. and len(self.trees_) &gt;= self.max_trees
  939. ):
  940. # If the node is the root of a new tree and we have reached self.max_trees,
  941. # don&#39;t split on it, but allow later splits to continue growing existing trees
  942. continue
  943. # split on node
  944. if verbose:
  945. print(&#34;\nadding &#34; + str(split_node))
  946. self.complexity_ += 1
  947. # if added a tree root
  948. if split_node.is_root:
  949. # start a new tree
  950. self.trees_.append(split_node)
  951. # update tree_num
  952. for node_ in [split_node, split_node.left_temp, split_node.right_temp]:
  953. if node_ is not None:
  954. node_.tree_num = len(self.trees_) - 1
  955. # add new root potential node
  956. node_new_root = Node(
  957. is_root=True, idxs=np.ones(X.shape[0], dtype=bool), tree_num=-1
  958. )
  959. potential_splits.append(node_new_root)
  960. # add children to potential splits
  961. # assign left_temp, right_temp to be proper children
  962. # (basically adds them to tree in predict method)
  963. split_node.setattrs(left=split_node.left_temp, right=split_node.right_temp)
  964. # add children to potential_splits
  965. potential_splits.append(split_node.left)
  966. potential_splits.append(split_node.right)
  967. # update predictions for altered tree
  968. for tree_num_ in range(len(self.trees_)):
  969. y_predictions_per_tree[tree_num_] = self._predict_tree(
  970. self.trees_[tree_num_], X
  971. )
  972. # dummy 0 preds for possible new trees
  973. y_predictions_per_tree[-1] = np.zeros(X.shape[0])
  974. # update residuals for each tree
  975. # -1 is key for potential new tree
  976. for tree_num_ in list(range(len(self.trees_))) + [-1]:
  977. y_residuals_per_tree[tree_num_] = deepcopy(y)
  978. # subtract predictions of all other trees
  979. # Since the current tree makes a constant prediction over the node being split,
  980. # one may ignore its contributions to the residuals without affecting the impurity decrease.
  981. for tree_num_other_ in range(len(self.trees_)):
  982. if not tree_num_other_ == tree_num_:
  983. y_residuals_per_tree[tree_num_] -= y_predictions_per_tree[
  984. tree_num_other_
  985. ]
  986. # recompute all impurities + update potential_split children
  987. potential_splits_new = []
  988. for potential_split in potential_splits:
  989. y_target = y_residuals_per_tree[potential_split.tree_num]
  990. # re-calculate the best split
  991. potential_split_updated = self._construct_node_with_stump(
  992. X=X,
  993. y=y_target,
  994. idxs=potential_split.idxs,
  995. tree_num=potential_split.tree_num,
  996. sample_weight=sample_weight,
  997. max_features=self.max_features,
  998. )
  999. # need to preserve certain attributes from before (value at this split + is_root)
  1000. # value may change because residuals may have changed, but we want it to store the value from before
  1001. potential_split.setattrs(
  1002. feature=potential_split_updated.feature,
  1003. threshold=potential_split_updated.threshold,
  1004. impurity_reduction=potential_split_updated.impurity_reduction,
  1005. impurity=potential_split_updated.impurity,
  1006. left_temp=potential_split_updated.left_temp,
  1007. right_temp=potential_split_updated.right_temp,
  1008. )
  1009. # this is a valid split
  1010. if potential_split.impurity_reduction is not None:
  1011. potential_splits_new.append(potential_split)
  1012. # sort so largest impurity reduction comes last (should probs make this a heap later)
  1013. potential_splits = sorted(
  1014. potential_splits_new, key=lambda x: x.impurity_reduction
  1015. )
  1016. if verbose:
  1017. print(self)
  1018. if self.max_rules is not None and self.complexity_ &gt;= self.max_rules:
  1019. finished = True
  1020. break
  1021. # annotate final tree with node_id and value_sklearn, and prepare importance_data_
  1022. importance_data = []
  1023. for tree_ in self.trees_:
  1024. node_counter = iter(range(0, int(1e06)))
  1025. def _annotate_node(node: Node, X, y):
  1026. if node is None:
  1027. return
  1028. # TODO does not incorporate sample weights
  1029. value_counts = pd.Series(y).value_counts()
  1030. try:
  1031. neg_count = value_counts[0.0]
  1032. except KeyError:
  1033. neg_count = 0
  1034. try:
  1035. pos_count = value_counts[1.0]
  1036. except KeyError:
  1037. pos_count = 0
  1038. value_sklearn = np.array([neg_count, pos_count], dtype=float)
  1039. node.setattrs(node_id=next(node_counter), value_sklearn=value_sklearn)
  1040. idxs_left = X[:, node.feature] &lt;= node.threshold
  1041. _annotate_node(node.left, X[idxs_left], y[idxs_left])
  1042. _annotate_node(node.right, X[~idxs_left], y[~idxs_left])
  1043. _annotate_node(tree_, X, y)
  1044. # now that the samples per node are known, we can start to compute the importances
  1045. importance_data_tree = np.zeros(len(self.feature_names_))
  1046. def _importances(node: Node):
  1047. if node is None or node.left is None:
  1048. return 0.0
  1049. # TODO does not incorporate sample weights, but will if added to value_sklearn
  1050. importance_data_tree[node.feature] += (
  1051. np.sum(node.value_sklearn) * node.impurity
  1052. - np.sum(node.left.value_sklearn) * node.left.impurity
  1053. - np.sum(node.right.value_sklearn) * node.right.impurity
  1054. )
  1055. return (
  1056. np.sum(node.value_sklearn)
  1057. + _importances(node.left)
  1058. + _importances(node.right)
  1059. )
  1060. # require the tree to have more than 1 node, otherwise just leave importance_data_tree as zeros
  1061. if 1 &lt; next(node_counter):
  1062. tree_samples = _importances(tree_)
  1063. if tree_samples != 0:
  1064. importance_data_tree /= tree_samples
  1065. else:
  1066. importance_data_tree = 0
  1067. importance_data.append(importance_data_tree)
  1068. self.importance_data_ = importance_data
  1069. return self
  1070. def _tree_to_str(self, root: Node, prefix=&#34;&#34;):
  1071. if root is None:
  1072. return &#34;&#34;
  1073. elif root.threshold is None:
  1074. return &#34;&#34;
  1075. pprefix = prefix + &#34;\t&#34;
  1076. return (
  1077. prefix
  1078. + str(root)
  1079. + &#34;\n&#34;
  1080. + self._tree_to_str(root.left, pprefix)
  1081. + self._tree_to_str(root.right, pprefix)
  1082. )
  1083. def _tree_to_str_with_data(self, X, y, root: Node, prefix=&#34;&#34;):
  1084. if root is None:
  1085. return &#34;&#34;
  1086. elif root.threshold is None:
  1087. return &#34;&#34;
  1088. pprefix = prefix + &#34;\t&#34;
  1089. left = X[:, root.feature] &lt;= root.threshold
  1090. return (
  1091. prefix
  1092. + root.print_root(y)
  1093. + &#34;\n&#34;
  1094. + self._tree_to_str_with_data(X[left], y[left], root.left, pprefix)
  1095. + self._tree_to_str_with_data(X[~left], y[~left], root.right, pprefix)
  1096. )
  1097. def __str__(self):
  1098. if not hasattr(self, &#34;trees_&#34;):
  1099. s = self.__class__.__name__
  1100. s += &#34;(&#34;
  1101. s += &#34;max_rules=&#34;
  1102. s += repr(self.max_rules)
  1103. s += &#34;)&#34;
  1104. return s
  1105. else:
  1106. s = &#34;&gt; ------------------------------\n&#34;
  1107. s += &#34;&gt; FIGS-Fast Interpretable Greedy-Tree Sums:\n&#34;
  1108. s += &#39;&gt; \tPredictions are made by summing the &#34;Val&#34; reached by traversing each tree.\n&#39;
  1109. s += &#34;&gt; \tFor classifiers, a sigmoid function is then applied to the sum.\n&#34;
  1110. s += &#34;&gt; ------------------------------\n&#34;
  1111. s += &#34;\n\t+\n&#34;.join([self._tree_to_str(t) for t in self.trees_])
  1112. if hasattr(self, &#34;feature_names_&#34;) and self.feature_names_ is not None:
  1113. for i in range(len(self.feature_names_))[::-1]:
  1114. s = s.replace(f&#34;X_{i}&#34;, self.feature_names_[i])
  1115. return s
  1116. def print_tree(self, X, y, feature_names=None):
  1117. s = &#34;------------\n&#34; + &#34;\n\t+\n&#34;.join(
  1118. [self._tree_to_str_with_data(X, y, t) for t in self.trees_]
  1119. )
  1120. if feature_names is None:
  1121. if hasattr(self, &#34;feature_names_&#34;) and self.feature_names_ is not None:
  1122. feature_names = self.feature_names_
  1123. if feature_names is not None:
  1124. for i in range(len(feature_names))[::-1]:
  1125. s = s.replace(f&#34;X_{i}&#34;, feature_names[i])
  1126. return s
  1127. def predict(self, X, categorical_features=None):
  1128. if hasattr(self, &#34;_encoder&#34;):
  1129. X = self._encode_categories(X, categorical_features=categorical_features)
  1130. X = check_array(X)
  1131. preds = np.zeros(X.shape[0])
  1132. for tree in self.trees_:
  1133. preds += self._predict_tree(tree, X)
  1134. if isinstance(self, RegressorMixin):
  1135. return preds
  1136. elif isinstance(self, ClassifierMixin):
  1137. return (preds &gt; 0.5).astype(int)
  1138. def predict_proba(self, X, categorical_features=None, use_clipped_prediction=False):
  1139. &#34;&#34;&#34;Predict probability for classifiers:
  1140. Default behavior is to constrain the outputs to the range of probabilities, i.e. 0 to 1, with a sigmoid function.
  1141. Set use_clipped_prediction=True to use prior behavior of clipping between 0 and 1 instead.
  1142. &#34;&#34;&#34;
  1143. if hasattr(self, &#34;_encoder&#34;):
  1144. X = self._encode_categories(X, categorical_features=categorical_features)
  1145. X = check_array(X)
  1146. if isinstance(self, RegressorMixin):
  1147. return NotImplemented
  1148. preds = np.zeros(X.shape[0])
  1149. for tree in self.trees_:
  1150. preds += self._predict_tree(tree, X)
  1151. if use_clipped_prediction:
  1152. # old behavior, pre v1.3.9
  1153. # constrain to range of probabilities by clipping
  1154. preds = np.clip(preds, a_min=0.0, a_max=1.0)
  1155. else:
  1156. # constrain to range of probabilities with a sigmoid function
  1157. preds = expit(preds)
  1158. return np.vstack((1 - preds, preds)).transpose()
  1159. def _predict_tree(self, root: Node, X):
  1160. &#34;&#34;&#34;Predict for a single tree&#34;&#34;&#34;
  1161. def _predict_tree_single_point(root: Node, x):
  1162. if root.left is None and root.right is None:
  1163. return root.value[0, 0]
  1164. left = x[root.feature] &lt;= root.threshold
  1165. if left:
  1166. if root.left is None: # we don&#39;t actually have to worry about this case
  1167. return root.value
  1168. else:
  1169. return _predict_tree_single_point(root.left, x)
  1170. else:
  1171. if (
  1172. root.right is None
  1173. ): # we don&#39;t actually have to worry about this case
  1174. return root.value
  1175. else:
  1176. return _predict_tree_single_point(root.right, x)
  1177. preds = np.zeros(X.shape[0])
  1178. for i in range(X.shape[0]):
  1179. preds[i] = _predict_tree_single_point(root, X[i])
  1180. return preds
  1181. @property
  1182. def feature_importances_(self):
  1183. &#34;&#34;&#34;Gini impurity-based feature importances&#34;&#34;&#34;
  1184. check_is_fitted(self)
  1185. avg_feature_importances = np.mean(
  1186. self.importance_data_, axis=0, dtype=np.float64
  1187. )
  1188. return avg_feature_importances / np.sum(avg_feature_importances)
  1189. def plot(
  1190. self,
  1191. cols=2,
  1192. feature_names=None,
  1193. filename=None,
  1194. label=&#34;all&#34;,
  1195. impurity=False,
  1196. tree_number=None,
  1197. dpi=150,
  1198. fig_size=None,
  1199. ):
  1200. is_single_tree = len(self.trees_) &lt; 2 or tree_number is not None
  1201. n_cols = int(cols)
  1202. n_rows = int(np.ceil(len(self.trees_) / n_cols))
  1203. if feature_names is None:
  1204. if hasattr(self, &#34;feature_names_&#34;) and self.feature_names_ is not None:
  1205. feature_names = self.feature_names_
  1206. n_plots = int(len(self.trees_)) if tree_number is None else 1
  1207. fig, axs = plt.subplots(n_plots, dpi=dpi)
  1208. if fig_size is not None:
  1209. fig.set_size_inches(fig_size, fig_size)
  1210. n_classes = 1 if isinstance(self, RegressorMixin) else 2
  1211. ax_size = int(len(self.trees_))
  1212. for i in range(n_plots):
  1213. r = i // n_cols
  1214. c = i % n_cols
  1215. if not is_single_tree:
  1216. ax = axs[i]
  1217. else:
  1218. ax = axs
  1219. try:
  1220. dt = extract_sklearn_tree_from_figs(
  1221. self, i if tree_number is None else tree_number, n_classes
  1222. )
  1223. plot_tree(
  1224. dt,
  1225. ax=ax,
  1226. feature_names=feature_names,
  1227. label=label,
  1228. impurity=impurity,
  1229. )
  1230. except IndexError:
  1231. ax.axis(&#34;off&#34;)
  1232. continue
  1233. ttl = f&#34;Tree {i}&#34; if n_plots &gt; 1 else f&#34;Tree {tree_number}&#34;
  1234. ax.set_title(ttl)
  1235. if filename is not None:
  1236. plt.savefig(filename)
  1237. return
  1238. plt.show()</code></pre>
  1239. </details>
  1240. <h3>Ancestors</h3>
  1241. <ul class="hlist">
  1242. <li>sklearn.base.BaseEstimator</li>
  1243. <li>sklearn.utils._estimator_html_repr._HTMLDocumentationLinkMixin</li>
  1244. <li>sklearn.utils._metadata_requests._MetadataRequester</li>
  1245. </ul>
  1246. <h3>Subclasses</h3>
  1247. <ul class="hlist">
  1248. <li><a title="imodels.tree.figs.FIGSClassifier" href="#imodels.tree.figs.FIGSClassifier">FIGSClassifier</a></li>
  1249. <li><a title="imodels.tree.figs.FIGSRegressor" href="#imodels.tree.figs.FIGSRegressor">FIGSRegressor</a></li>
  1250. </ul>
  1251. <h3>Instance variables</h3>
  1252. <dl>
  1253. <dt id="imodels.tree.figs.FIGS.feature_importances_"><code class="name">var <span class="ident">feature_importances_</span></code></dt>
  1254. <dd>
  1255. <div class="desc"><p>Gini impurity-based feature importances</p></div>
  1256. <details class="source">
  1257. <summary>
  1258. <span>Expand source code</span>
  1259. </summary>
  1260. <pre><code class="python">@property
  1261. def feature_importances_(self):
  1262. &#34;&#34;&#34;Gini impurity-based feature importances&#34;&#34;&#34;
  1263. check_is_fitted(self)
  1264. avg_feature_importances = np.mean(
  1265. self.importance_data_, axis=0, dtype=np.float64
  1266. )
  1267. return avg_feature_importances / np.sum(avg_feature_importances)</code></pre>
  1268. </details>
  1269. </dd>
  1270. </dl>
  1271. <h3>Methods</h3>
  1272. <dl>
  1273. <dt id="imodels.tree.figs.FIGS.fit"><code class="name flex">
  1274. <span>def <span class="ident">fit</span></span>(<span>self, X, y=None, feature_names=None, verbose=False, sample_weight=None, categorical_features=None)</span>
  1275. </code></dt>
  1276. <dd>
  1277. <div class="desc"><h2 id="params">Params</h2>
  1278. <p>_sample_weight: array-like of shape (n_samples,), default=None
  1279. Sample weights. If None, then samples are equally weighted.
  1280. Splits that would create child nodes with net zero or negative weight
  1281. are ignored while searching for a split in each node.</p></div>
  1282. <details class="source">
  1283. <summary>
  1284. <span>Expand source code</span>
  1285. </summary>
  1286. <pre><code class="python">def fit(
  1287. self,
  1288. X,
  1289. y=None,
  1290. feature_names=None,
  1291. verbose=False,
  1292. sample_weight=None,
  1293. categorical_features=None,
  1294. ):
  1295. &#34;&#34;&#34;
  1296. Params
  1297. ------
  1298. _sample_weight: array-like of shape (n_samples,), default=None
  1299. Sample weights. If None, then samples are equally weighted.
  1300. Splits that would create child nodes with net zero or negative weight
  1301. are ignored while searching for a split in each node.
  1302. &#34;&#34;&#34;
  1303. if categorical_features is not None:
  1304. X, self._encoder = self._encode_categories(X, categorical_features)
  1305. X, y, feature_names = check_fit_arguments(self, X, y, feature_names)
  1306. if sample_weight is not None:
  1307. sample_weight = _check_sample_weight(sample_weight, X)
  1308. self.trees_ = [] # list of the root nodes of added trees
  1309. self.complexity_ = 0 # tracks the number of rules in the model
  1310. y_predictions_per_tree = {} # predictions for each tree
  1311. y_residuals_per_tree = {} # based on predictions above
  1312. # set up initial potential_splits
  1313. # everything in potential_splits either is_root (so it can be added directly to self.trees_)
  1314. # or it is a child of a root node that has already been added
  1315. idxs = np.ones(X.shape[0], dtype=bool)
  1316. node_init = self._construct_node_with_stump(
  1317. X=X,
  1318. y=y,
  1319. idxs=idxs,
  1320. tree_num=-1,
  1321. sample_weight=sample_weight,
  1322. max_features=self.max_features,
  1323. )
  1324. potential_splits = [node_init]
  1325. for node in potential_splits:
  1326. node.setattrs(is_root=True)
  1327. potential_splits = sorted(potential_splits, key=lambda x: x.impurity_reduction)
  1328. # start the greedy fitting algorithm
  1329. finished = False
  1330. while len(potential_splits) &gt; 0 and not finished:
  1331. # print(&#39;potential_splits&#39;, [str(s) for s in potential_splits])
  1332. # get node with max impurity_reduction (since it&#39;s sorted)
  1333. split_node = potential_splits.pop()
  1334. # don&#39;t split on node
  1335. if split_node.impurity_reduction &lt; self.min_impurity_decrease:
  1336. finished = True
  1337. break
  1338. elif (
  1339. split_node.is_root
  1340. and self.max_trees is not None
  1341. and len(self.trees_) &gt;= self.max_trees
  1342. ):
  1343. # If the node is the root of a new tree and we have reached self.max_trees,
  1344. # don&#39;t split on it, but allow later splits to continue growing existing trees
  1345. continue
  1346. # split on node
  1347. if verbose:
  1348. print(&#34;\nadding &#34; + str(split_node))
  1349. self.complexity_ += 1
  1350. # if added a tree root
  1351. if split_node.is_root:
  1352. # start a new tree
  1353. self.trees_.append(split_node)
  1354. # update tree_num
  1355. for node_ in [split_node, split_node.left_temp, split_node.right_temp]:
  1356. if node_ is not None:
  1357. node_.tree_num = len(self.trees_) - 1
  1358. # add new root potential node
  1359. node_new_root = Node(
  1360. is_root=True, idxs=np.ones(X.shape[0], dtype=bool), tree_num=-1
  1361. )
  1362. potential_splits.append(node_new_root)
  1363. # add children to potential splits
  1364. # assign left_temp, right_temp to be proper children
  1365. # (basically adds them to tree in predict method)
  1366. split_node.setattrs(left=split_node.left_temp, right=split_node.right_temp)
  1367. # add children to potential_splits
  1368. potential_splits.append(split_node.left)
  1369. potential_splits.append(split_node.right)
  1370. # update predictions for altered tree
  1371. for tree_num_ in range(len(self.trees_)):
  1372. y_predictions_per_tree[tree_num_] = self._predict_tree(
  1373. self.trees_[tree_num_], X
  1374. )
  1375. # dummy 0 preds for possible new trees
  1376. y_predictions_per_tree[-1] = np.zeros(X.shape[0])
  1377. # update residuals for each tree
  1378. # -1 is key for potential new tree
  1379. for tree_num_ in list(range(len(self.trees_))) + [-1]:
  1380. y_residuals_per_tree[tree_num_] = deepcopy(y)
  1381. # subtract predictions of all other trees
  1382. # Since the current tree makes a constant prediction over the node being split,
  1383. # one may ignore its contributions to the residuals without affecting the impurity decrease.
  1384. for tree_num_other_ in range(len(self.trees_)):
  1385. if not tree_num_other_ == tree_num_:
  1386. y_residuals_per_tree[tree_num_] -= y_predictions_per_tree[
  1387. tree_num_other_
  1388. ]
  1389. # recompute all impurities + update potential_split children
  1390. potential_splits_new = []
  1391. for potential_split in potential_splits:
  1392. y_target = y_residuals_per_tree[potential_split.tree_num]
  1393. # re-calculate the best split
  1394. potential_split_updated = self._construct_node_with_stump(
  1395. X=X,
  1396. y=y_target,
  1397. idxs=potential_split.idxs,
  1398. tree_num=potential_split.tree_num,
  1399. sample_weight=sample_weight,
  1400. max_features=self.max_features,
  1401. )
  1402. # need to preserve certain attributes from before (value at this split + is_root)
  1403. # value may change because residuals may have changed, but we want it to store the value from before
  1404. potential_split.setattrs(
  1405. feature=potential_split_updated.feature,
  1406. threshold=potential_split_updated.threshold,
  1407. impurity_reduction=potential_split_updated.impurity_reduction,
  1408. impurity=potential_split_updated.impurity,
  1409. left_temp=potential_split_updated.left_temp,
  1410. right_temp=potential_split_updated.right_temp,
  1411. )
  1412. # this is a valid split
  1413. if potential_split.impurity_reduction is not None:
  1414. potential_splits_new.append(potential_split)
  1415. # sort so largest impurity reduction comes last (should probs make this a heap later)
  1416. potential_splits = sorted(
  1417. potential_splits_new, key=lambda x: x.impurity_reduction
  1418. )
  1419. if verbose:
  1420. print(self)
  1421. if self.max_rules is not None and self.complexity_ &gt;= self.max_rules:
  1422. finished = True
  1423. break
  1424. # annotate final tree with node_id and value_sklearn, and prepare importance_data_
  1425. importance_data = []
  1426. for tree_ in self.trees_:
  1427. node_counter = iter(range(0, int(1e06)))
  1428. def _annotate_node(node: Node, X, y):
  1429. if node is None:
  1430. return
  1431. # TODO does not incorporate sample weights
  1432. value_counts = pd.Series(y).value_counts()
  1433. try:
  1434. neg_count = value_counts[0.0]
  1435. except KeyError:
  1436. neg_count = 0
  1437. try:
  1438. pos_count = value_counts[1.0]
  1439. except KeyError:
  1440. pos_count = 0
  1441. value_sklearn = np.array([neg_count, pos_count], dtype=float)
  1442. node.setattrs(node_id=next(node_counter), value_sklearn=value_sklearn)
  1443. idxs_left = X[:, node.feature] &lt;= node.threshold
  1444. _annotate_node(node.left, X[idxs_left], y[idxs_left])
  1445. _annotate_node(node.right, X[~idxs_left], y[~idxs_left])
  1446. _annotate_node(tree_, X, y)
  1447. # now that the samples per node are known, we can start to compute the importances
  1448. importance_data_tree = np.zeros(len(self.feature_names_))
  1449. def _importances(node: Node):
  1450. if node is None or node.left is None:
  1451. return 0.0
  1452. # TODO does not incorporate sample weights, but will if added to value_sklearn
  1453. importance_data_tree[node.feature] += (
  1454. np.sum(node.value_sklearn) * node.impurity
  1455. - np.sum(node.left.value_sklearn) * node.left.impurity
  1456. - np.sum(node.right.value_sklearn) * node.right.impurity
  1457. )
  1458. return (
  1459. np.sum(node.value_sklearn)
  1460. + _importances(node.left)
  1461. + _importances(node.right)
  1462. )
  1463. # require the tree to have more than 1 node, otherwise just leave importance_data_tree as zeros
  1464. if 1 &lt; next(node_counter):
  1465. tree_samples = _importances(tree_)
  1466. if tree_samples != 0:
  1467. importance_data_tree /= tree_samples
  1468. else:
  1469. importance_data_tree = 0
  1470. importance_data.append(importance_data_tree)
  1471. self.importance_data_ = importance_data
  1472. return self</code></pre>
  1473. </details>
  1474. </dd>
  1475. <dt id="imodels.tree.figs.FIGS.plot"><code class="name flex">
  1476. <span>def <span class="ident">plot</span></span>(<span>self, cols=2, feature_names=None, filename=None, label='all', impurity=False, tree_number=None, dpi=150, fig_size=None)</span>
  1477. </code></dt>
  1478. <dd>
  1479. <div class="desc"></div>
  1480. <details class="source">
  1481. <summary>
  1482. <span>Expand source code</span>
  1483. </summary>
  1484. <pre><code class="python">def plot(
  1485. self,
  1486. cols=2,
  1487. feature_names=None,
  1488. filename=None,
  1489. label=&#34;all&#34;,
  1490. impurity=False,
  1491. tree_number=None,
  1492. dpi=150,
  1493. fig_size=None,
  1494. ):
  1495. is_single_tree = len(self.trees_) &lt; 2 or tree_number is not None
  1496. n_cols = int(cols)
  1497. n_rows = int(np.ceil(len(self.trees_) / n_cols))
  1498. if feature_names is None:
  1499. if hasattr(self, &#34;feature_names_&#34;) and self.feature_names_ is not None:
  1500. feature_names = self.feature_names_
  1501. n_plots = int(len(self.trees_)) if tree_number is None else 1
  1502. fig, axs = plt.subplots(n_plots, dpi=dpi)
  1503. if fig_size is not None:
  1504. fig.set_size_inches(fig_size, fig_size)
  1505. n_classes = 1 if isinstance(self, RegressorMixin) else 2
  1506. ax_size = int(len(self.trees_))
  1507. for i in range(n_plots):
  1508. r = i // n_cols
  1509. c = i % n_cols
  1510. if not is_single_tree:
  1511. ax = axs[i]
  1512. else:
  1513. ax = axs
  1514. try:
  1515. dt = extract_sklearn_tree_from_figs(
  1516. self, i if tree_number is None else tree_number, n_classes
  1517. )
  1518. plot_tree(
  1519. dt,
  1520. ax=ax,
  1521. feature_names=feature_names,
  1522. label=label,
  1523. impurity=impurity,
  1524. )
  1525. except IndexError:
  1526. ax.axis(&#34;off&#34;)
  1527. continue
  1528. ttl = f&#34;Tree {i}&#34; if n_plots &gt; 1 else f&#34;Tree {tree_number}&#34;
  1529. ax.set_title(ttl)
  1530. if filename is not None:
  1531. plt.savefig(filename)
  1532. return
  1533. plt.show()</code></pre>
  1534. </details>
  1535. </dd>
  1536. <dt id="imodels.tree.figs.FIGS.predict"><code class="name flex">
  1537. <span>def <span class="ident">predict</span></span>(<span>self, X, categorical_features=None)</span>
  1538. </code></dt>
  1539. <dd>
  1540. <div class="desc"></div>
  1541. <details class="source">
  1542. <summary>
  1543. <span>Expand source code</span>
  1544. </summary>
  1545. <pre><code class="python">def predict(self, X, categorical_features=None):
  1546. if hasattr(self, &#34;_encoder&#34;):
  1547. X = self._encode_categories(X, categorical_features=categorical_features)
  1548. X = check_array(X)
  1549. preds = np.zeros(X.shape[0])
  1550. for tree in self.trees_:
  1551. preds += self._predict_tree(tree, X)
  1552. if isinstance(self, RegressorMixin):
  1553. return preds
  1554. elif isinstance(self, ClassifierMixin):
  1555. return (preds &gt; 0.5).astype(int)</code></pre>
  1556. </details>
  1557. </dd>
  1558. <dt id="imodels.tree.figs.FIGS.predict_proba"><code class="name flex">
  1559. <span>def <span class="ident">predict_proba</span></span>(<span>self, X, categorical_features=None, use_clipped_prediction=False)</span>
  1560. </code></dt>
  1561. <dd>
  1562. <div class="desc"><p>Predict probability for classifiers:
  1563. Default behavior is to constrain the outputs to the range of probabilities, i.e. 0 to 1, with a sigmoid function.
  1564. Set use_clipped_prediction=True to use prior behavior of clipping between 0 and 1 instead.</p></div>
  1565. <details class="source">
  1566. <summary>
  1567. <span>Expand source code</span>
  1568. </summary>
  1569. <pre><code class="python">def predict_proba(self, X, categorical_features=None, use_clipped_prediction=False):
  1570. &#34;&#34;&#34;Predict probability for classifiers:
  1571. Default behavior is to constrain the outputs to the range of probabilities, i.e. 0 to 1, with a sigmoid function.
  1572. Set use_clipped_prediction=True to use prior behavior of clipping between 0 and 1 instead.
  1573. &#34;&#34;&#34;
  1574. if hasattr(self, &#34;_encoder&#34;):
  1575. X = self._encode_categories(X, categorical_features=categorical_features)
  1576. X = check_array(X)
  1577. if isinstance(self, RegressorMixin):
  1578. return NotImplemented
  1579. preds = np.zeros(X.shape[0])
  1580. for tree in self.trees_:
  1581. preds += self._predict_tree(tree, X)
  1582. if use_clipped_prediction:
  1583. # old behavior, pre v1.3.9
  1584. # constrain to range of probabilities by clipping
  1585. preds = np.clip(preds, a_min=0.0, a_max=1.0)
  1586. else:
  1587. # constrain to range of probabilities with a sigmoid function
  1588. preds = expit(preds)
  1589. return np.vstack((1 - preds, preds)).transpose()</code></pre>
  1590. </details>
  1591. </dd>
  1592. <dt id="imodels.tree.figs.FIGS.print_tree"><code class="name flex">
  1593. <span>def <span class="ident">print_tree</span></span>(<span>self, X, y, feature_names=None)</span>
  1594. </code></dt>
  1595. <dd>
  1596. <div class="desc"></div>
  1597. <details class="source">
  1598. <summary>
  1599. <span>Expand source code</span>
  1600. </summary>
  1601. <pre><code class="python">def print_tree(self, X, y, feature_names=None):
  1602. s = &#34;------------\n&#34; + &#34;\n\t+\n&#34;.join(
  1603. [self._tree_to_str_with_data(X, y, t) for t in self.trees_]
  1604. )
  1605. if feature_names is None:
  1606. if hasattr(self, &#34;feature_names_&#34;) and self.feature_names_ is not None:
  1607. feature_names = self.feature_names_
  1608. if feature_names is not None:
  1609. for i in range(len(feature_names))[::-1]:
  1610. s = s.replace(f&#34;X_{i}&#34;, feature_names[i])
  1611. return s</code></pre>
  1612. </details>
  1613. </dd>
  1614. <dt id="imodels.tree.figs.FIGS.set_fit_request"><code class="name flex">
  1615. <span>def <span class="ident">set_fit_request</span></span>(<span>self: <a title="imodels.tree.figs.FIGS" href="#imodels.tree.figs.FIGS">FIGS</a>, *, categorical_features: Union[bool, ForwardRef(None), str] = '$UNCHANGED$', feature_names: Union[bool, ForwardRef(None), str] = '$UNCHANGED$', sample_weight: Union[bool, ForwardRef(None), str] = '$UNCHANGED$', verbose: Union[bool, ForwardRef(None), str] = '$UNCHANGED$') ‑> <a title="imodels.tree.figs.FIGS" href="#imodels.tree.figs.FIGS">FIGS</a></span>
  1616. </code></dt>
  1617. <dd>
  1618. <div class="desc"><p>Request metadata passed to the <code>fit</code> method.</p>
  1619. <p>Note that this method is only relevant if
  1620. <code>enable_metadata_routing=True</code> (see :func:<code>sklearn.set_config</code>).
  1621. Please see :ref:<code>User Guide &lt;metadata_routing&gt;</code> on how the routing
  1622. mechanism works.</p>
  1623. <p>The options for each parameter are:</p>
  1624. <ul>
  1625. <li>
  1626. <p><code>True</code>: metadata is requested, and passed to <code>fit</code> if provided. The request is ignored if metadata is not provided.</p>
  1627. </li>
  1628. <li>
  1629. <p><code>False</code>: metadata is not requested and the meta-estimator will not pass it to <code>fit</code>.</p>
  1630. </li>
  1631. <li>
  1632. <p><code>None</code>: metadata is not requested, and the meta-estimator will raise an error if the user provides it.</p>
  1633. </li>
  1634. <li>
  1635. <p><code>str</code>: metadata should be passed to the meta-estimator with this given alias instead of the original name.</p>
  1636. </li>
  1637. </ul>
  1638. <p>The default (<code>sklearn.utils.metadata_routing.UNCHANGED</code>) retains the
  1639. existing request. This allows you to change the request for some
  1640. parameters and not others.</p>
  1641. <div class="admonition versionadded">
  1642. <p class="admonition-title">Added in version:&ensp;1.3</p>
  1643. </div>
  1644. <div class="admonition note">
  1645. <p class="admonition-title">Note</p>
  1646. <p>This method is only relevant if this estimator is used as a
  1647. sub-estimator of a meta-estimator, e.g. used inside a
  1648. :class:<code>~sklearn.pipeline.Pipeline</code>. Otherwise it has no effect.</p>
  1649. </div>
  1650. <h2 id="parameters">Parameters</h2>
  1651. <dl>
  1652. <dt><strong><code>categorical_features</code></strong> :&ensp;<code>str, True, False,</code> or <code>None</code>,
  1653. default=<code>sklearn.utils.metadata_routing.UNCHANGED</code></dt>
  1654. <dd>Metadata routing for <code>categorical_features</code> parameter in <code>fit</code>.</dd>
  1655. <dt><strong><code>feature_names</code></strong> :&ensp;<code>str, True, False,</code> or <code>None</code>,
  1656. default=<code>sklearn.utils.metadata_routing.UNCHANGED</code></dt>
  1657. <dd>Metadata routing for <code>feature_names</code> parameter in <code>fit</code>.</dd>
  1658. <dt><strong><code>sample_weight</code></strong> :&ensp;<code>str, True, False,</code> or <code>None</code>,
  1659. default=<code>sklearn.utils.metadata_routing.UNCHANGED</code></dt>
  1660. <dd>Metadata routing for <code>sample_weight</code> parameter in <code>fit</code>.</dd>
  1661. <dt><strong><code>verbose</code></strong> :&ensp;<code>str, True, False,</code> or <code>None</code>,
  1662. default=<code>sklearn.utils.metadata_routing.UNCHANGED</code></dt>
  1663. <dd>Metadata routing for <code>verbose</code> parameter in <code>fit</code>.</dd>
  1664. </dl>
  1665. <h2 id="returns">Returns</h2>
  1666. <dl>
  1667. <dt><strong><code>self</code></strong> :&ensp;<code>object</code></dt>
  1668. <dd>The updated object.</dd>
  1669. </dl></div>
  1670. <details class="source">
  1671. <summary>
  1672. <span>Expand source code</span>
  1673. </summary>
  1674. <pre><code class="python">def func(**kw):
  1675. &#34;&#34;&#34;Updates the request for provided parameters
  1676. This docstring is overwritten below.
  1677. See REQUESTER_DOC for expected functionality
  1678. &#34;&#34;&#34;
  1679. if not _routing_enabled():
  1680. raise RuntimeError(
  1681. &#34;This method is only available when metadata routing is enabled.&#34;
  1682. &#34; You can enable it using&#34;
  1683. &#34; sklearn.set_config(enable_metadata_routing=True).&#34;
  1684. )
  1685. if self.validate_keys and (set(kw) - set(self.keys)):
  1686. raise TypeError(
  1687. f&#34;Unexpected args: {set(kw) - set(self.keys)}. Accepted arguments&#34;
  1688. f&#34; are: {set(self.keys)}&#34;
  1689. )
  1690. requests = instance._get_metadata_request()
  1691. method_metadata_request = getattr(requests, self.name)
  1692. for prop, alias in kw.items():
  1693. if alias is not UNCHANGED:
  1694. method_metadata_request.add_request(param=prop, alias=alias)
  1695. instance._metadata_request = requests
  1696. return instance</code></pre>
  1697. </details>
  1698. </dd>
  1699. <dt id="imodels.tree.figs.FIGS.set_predict_proba_request"><code class="name flex">
  1700. <span>def <span class="ident">set_predict_proba_request</span></span>(<span>self: <a title="imodels.tree.figs.FIGS" href="#imodels.tree.figs.FIGS">FIGS</a>, *, categorical_features: Union[bool, ForwardRef(None), str] = '$UNCHANGED$', use_clipped_prediction: Union[bool, ForwardRef(None), str] = '$UNCHANGED$') ‑> <a title="imodels.tree.figs.FIGS" href="#imodels.tree.figs.FIGS">FIGS</a></span>
  1701. </code></dt>
  1702. <dd>
  1703. <div class="desc"><p>Request metadata passed to the <code>predict_proba</code> method.</p>
  1704. <p>Note that this method is only relevant if
  1705. <code>enable_metadata_routing=True</code> (see :func:<code>sklearn.set_config</code>).
  1706. Please see :ref:<code>User Guide &lt;metadata_routing&gt;</code> on how the routing
  1707. mechanism works.</p>
  1708. <p>The options for each parameter are:</p>
  1709. <ul>
  1710. <li>
  1711. <p><code>True</code>: metadata is requested, and passed to <code>predict_proba</code> if provided. The request is ignored if metadata is not provided.</p>
  1712. </li>
  1713. <li>
  1714. <p><code>False</code>: metadata is not requested and the meta-estimator will not pass it to <code>predict_proba</code>.</p>
  1715. </li>
  1716. <li>
  1717. <p><code>None</code>: metadata is not requested, and the meta-estimator will raise an error if the user provides it.</p>
  1718. </li>
  1719. <li>
  1720. <p><code>str</code>: metadata should be passed to the meta-estimator with this given alias instead of the original name.</p>
  1721. </li>
  1722. </ul>
  1723. <p>The default (<code>sklearn.utils.metadata_routing.UNCHANGED</code>) retains the
  1724. existing request. This allows you to change the request for some
  1725. parameters and not others.</p>
  1726. <div class="admonition versionadded">
  1727. <p class="admonition-title">Added in version:&ensp;1.3</p>
  1728. </div>
  1729. <div class="admonition note">
  1730. <p class="admonition-title">Note</p>
  1731. <p>This method is only relevant if this estimator is used as a
  1732. sub-estimator of a meta-estimator, e.g. used inside a
  1733. :class:<code>~sklearn.pipeline.Pipeline</code>. Otherwise it has no effect.</p>
  1734. </div>
  1735. <h2 id="parameters">Parameters</h2>
  1736. <dl>
  1737. <dt><strong><code>categorical_features</code></strong> :&ensp;<code>str, True, False,</code> or <code>None</code>,
  1738. default=<code>sklearn.utils.metadata_routing.UNCHANGED</code></dt>
  1739. <dd>Metadata routing for <code>categorical_features</code> parameter in <code>predict_proba</code>.</dd>
  1740. <dt><strong><code>use_clipped_prediction</code></strong> :&ensp;<code>str, True, False,</code> or <code>None</code>,
  1741. default=<code>sklearn.utils.metadata_routing.UNCHANGED</code></dt>
  1742. <dd>Metadata routing for <code>use_clipped_prediction</code> parameter in <code>predict_proba</code>.</dd>
  1743. </dl>
  1744. <h2 id="returns">Returns</h2>
  1745. <dl>
  1746. <dt><strong><code>self</code></strong> :&ensp;<code>object</code></dt>
  1747. <dd>The updated object.</dd>
  1748. </dl></div>
  1749. <details class="source">
  1750. <summary>
  1751. <span>Expand source code</span>
  1752. </summary>
  1753. <pre><code class="python">def func(**kw):
  1754. &#34;&#34;&#34;Updates the request for provided parameters
  1755. This docstring is overwritten below.
  1756. See REQUESTER_DOC for expected functionality
  1757. &#34;&#34;&#34;
  1758. if not _routing_enabled():
  1759. raise RuntimeError(
  1760. &#34;This method is only available when metadata routing is enabled.&#34;
  1761. &#34; You can enable it using&#34;
  1762. &#34; sklearn.set_config(enable_metadata_routing=True).&#34;
  1763. )
  1764. if self.validate_keys and (set(kw) - set(self.keys)):
  1765. raise TypeError(
  1766. f&#34;Unexpected args: {set(kw) - set(self.keys)}. Accepted arguments&#34;
  1767. f&#34; are: {set(self.keys)}&#34;
  1768. )
  1769. requests = instance._get_metadata_request()
  1770. method_metadata_request = getattr(requests, self.name)
  1771. for prop, alias in kw.items():
  1772. if alias is not UNCHANGED:
  1773. method_metadata_request.add_request(param=prop, alias=alias)
  1774. instance._metadata_request = requests
  1775. return instance</code></pre>
  1776. </details>
  1777. </dd>
  1778. <dt id="imodels.tree.figs.FIGS.set_predict_request"><code class="name flex">
  1779. <span>def <span class="ident">set_predict_request</span></span>(<span>self: <a title="imodels.tree.figs.FIGS" href="#imodels.tree.figs.FIGS">FIGS</a>, *, categorical_features: Union[bool, ForwardRef(None), str] = '$UNCHANGED$') ‑> <a title="imodels.tree.figs.FIGS" href="#imodels.tree.figs.FIGS">FIGS</a></span>
  1780. </code></dt>
  1781. <dd>
  1782. <div class="desc"><p>Request metadata passed to the <code>predict</code> method.</p>
  1783. <p>Note that this method is only relevant if
  1784. <code>enable_metadata_routing=True</code> (see :func:<code>sklearn.set_config</code>).
  1785. Please see :ref:<code>User Guide &lt;metadata_routing&gt;</code> on how the routing
  1786. mechanism works.</p>
  1787. <p>The options for each parameter are:</p>
  1788. <ul>
  1789. <li>
  1790. <p><code>True</code>: metadata is requested, and passed to <code>predict</code> if provided. The request is ignored if metadata is not provided.</p>
  1791. </li>
  1792. <li>
  1793. <p><code>False</code>: metadata is not requested and the meta-estimator will not pass it to <code>predict</code>.</p>
  1794. </li>
  1795. <li>
  1796. <p><code>None</code>: metadata is not requested, and the meta-estimator will raise an error if the user provides it.</p>
  1797. </li>
  1798. <li>
  1799. <p><code>str</code>: metadata should be passed to the meta-estimator with this given alias instead of the original name.</p>
  1800. </li>
  1801. </ul>
  1802. <p>The default (<code>sklearn.utils.metadata_routing.UNCHANGED</code>) retains the
  1803. existing request. This allows you to change the request for some
  1804. parameters and not others.</p>
  1805. <div class="admonition versionadded">
  1806. <p class="admonition-title">Added in version:&ensp;1.3</p>
  1807. </div>
  1808. <div class="admonition note">
  1809. <p class="admonition-title">Note</p>
  1810. <p>This method is only relevant if this estimator is used as a
  1811. sub-estimator of a meta-estimator, e.g. used inside a
  1812. :class:<code>~sklearn.pipeline.Pipeline</code>. Otherwise it has no effect.</p>
  1813. </div>
  1814. <h2 id="parameters">Parameters</h2>
  1815. <dl>
  1816. <dt><strong><code>categorical_features</code></strong> :&ensp;<code>str, True, False,</code> or <code>None</code>,
  1817. default=<code>sklearn.utils.metadata_routing.UNCHANGED</code></dt>
  1818. <dd>Metadata routing for <code>categorical_features</code> parameter in <code>predict</code>.</dd>
  1819. </dl>
  1820. <h2 id="returns">Returns</h2>
  1821. <dl>
  1822. <dt><strong><code>self</code></strong> :&ensp;<code>object</code></dt>
  1823. <dd>The updated object.</dd>
  1824. </dl></div>
  1825. <details class="source">
  1826. <summary>
  1827. <span>Expand source code</span>
  1828. </summary>
  1829. <pre><code class="python">def func(**kw):
  1830. &#34;&#34;&#34;Updates the request for provided parameters
  1831. This docstring is overwritten below.
  1832. See REQUESTER_DOC for expected functionality
  1833. &#34;&#34;&#34;
  1834. if not _routing_enabled():
  1835. raise RuntimeError(
  1836. &#34;This method is only available when metadata routing is enabled.&#34;
  1837. &#34; You can enable it using&#34;
  1838. &#34; sklearn.set_config(enable_metadata_routing=True).&#34;
  1839. )
  1840. if self.validate_keys and (set(kw) - set(self.keys)):
  1841. raise TypeError(
  1842. f&#34;Unexpected args: {set(kw) - set(self.keys)}. Accepted arguments&#34;
  1843. f&#34; are: {set(self.keys)}&#34;
  1844. )
  1845. requests = instance._get_metadata_request()
  1846. method_metadata_request = getattr(requests, self.name)
  1847. for prop, alias in kw.items():
  1848. if alias is not UNCHANGED:
  1849. method_metadata_request.add_request(param=prop, alias=alias)
  1850. instance._metadata_request = requests
  1851. return instance</code></pre>
  1852. </details>
  1853. </dd>
  1854. </dl>
  1855. </dd>
  1856. <dt id="imodels.tree.figs.FIGSCV"><code class="flex name class">
  1857. <span>class <span class="ident">FIGSCV</span></span>
  1858. <span>(</span><span>figs, n_rules_list: List[int] = [6, 12, 24, 30, 50], n_trees_list: List[int] = [5, 5, 5, 5, 5], cv: int = 3, scoring=None, *args, **kwargs)</span>
  1859. </code></dt>
  1860. <dd>
  1861. <div class="desc"></div>
  1862. <details class="source">
  1863. <summary>
  1864. <span>Expand source code</span>
  1865. </summary>
  1866. <pre><code class="python">class FIGSCV:
  1867. def __init__(
  1868. self,
  1869. figs,
  1870. n_rules_list: List[int] = [6, 12, 24, 30, 50],
  1871. n_trees_list: List[int] = [5, 5, 5, 5, 5],
  1872. cv: int = 3,
  1873. scoring=None,
  1874. *args,
  1875. **kwargs,
  1876. ):
  1877. if len(n_rules_list) != len(n_trees_list):
  1878. raise ValueError(
  1879. f&#34;len(n_rules_list) = {len(n_rules_list)} != len(n_trees_list) = {len(n_trees_list)}&#34;
  1880. )
  1881. self._figs_class = figs
  1882. self.n_rules_list = np.array(n_rules_list)
  1883. self.n_trees_list = np.array(n_trees_list)
  1884. self.cv = cv
  1885. self.scoring = scoring
  1886. def fit(self, X, y):
  1887. self.scores_ = []
  1888. for _i, n_rules in enumerate(self.n_rules_list):
  1889. est = self._figs_class(max_rules=n_rules, max_trees=self.n_trees_list[_i])
  1890. cv_scores = cross_val_score(est, X, y, cv=self.cv, scoring=self.scoring)
  1891. mean_score = np.mean(cv_scores)
  1892. if len(self.scores_) == 0:
  1893. self.figs = est
  1894. elif mean_score &gt; np.max(self.scores_):
  1895. self.figs = est
  1896. self.scores_.append(mean_score)
  1897. self.figs.fit(X=X, y=y)
  1898. def predict_proba(self, X):
  1899. return self.figs.predict_proba(X)
  1900. def predict(self, X):
  1901. return self.figs.predict(X)
  1902. @property
  1903. def max_rules(self):
  1904. return self.figs.max_rules
  1905. @property
  1906. def max_trees(self):
  1907. return self.figs.max_trees</code></pre>
  1908. </details>
  1909. <h3>Subclasses</h3>
  1910. <ul class="hlist">
  1911. <li><a title="imodels.tree.figs.FIGSClassifierCV" href="#imodels.tree.figs.FIGSClassifierCV">FIGSClassifierCV</a></li>
  1912. <li><a title="imodels.tree.figs.FIGSRegressorCV" href="#imodels.tree.figs.FIGSRegressorCV">FIGSRegressorCV</a></li>
  1913. </ul>
  1914. <h3>Instance variables</h3>
  1915. <dl>
  1916. <dt id="imodels.tree.figs.FIGSCV.max_rules"><code class="name">var <span class="ident">max_rules</span></code></dt>
  1917. <dd>
  1918. <div class="desc"></div>
  1919. <details class="source">
  1920. <summary>
  1921. <span>Expand source code</span>
  1922. </summary>
  1923. <pre><code class="python">@property
  1924. def max_rules(self):
  1925. return self.figs.max_rules</code></pre>
  1926. </details>
  1927. </dd>
  1928. <dt id="imodels.tree.figs.FIGSCV.max_trees"><code class="name">var <span class="ident">max_trees</span></code></dt>
  1929. <dd>
  1930. <div class="desc"></div>
  1931. <details class="source">
  1932. <summary>
  1933. <span>Expand source code</span>
  1934. </summary>
  1935. <pre><code class="python">@property
  1936. def max_trees(self):
  1937. return self.figs.max_trees</code></pre>
  1938. </details>
  1939. </dd>
  1940. </dl>
  1941. <h3>Methods</h3>
  1942. <dl>
  1943. <dt id="imodels.tree.figs.FIGSCV.fit"><code class="name flex">
  1944. <span>def <span class="ident">fit</span></span>(<span>self, X, y)</span>
  1945. </code></dt>
  1946. <dd>
  1947. <div class="desc"></div>
  1948. <details class="source">
  1949. <summary>
  1950. <span>Expand source code</span>
  1951. </summary>
  1952. <pre><code class="python">def fit(self, X, y):
  1953. self.scores_ = []
  1954. for _i, n_rules in enumerate(self.n_rules_list):
  1955. est = self._figs_class(max_rules=n_rules, max_trees=self.n_trees_list[_i])
  1956. cv_scores = cross_val_score(est, X, y, cv=self.cv, scoring=self.scoring)
  1957. mean_score = np.mean(cv_scores)
  1958. if len(self.scores_) == 0:
  1959. self.figs = est
  1960. elif mean_score &gt; np.max(self.scores_):
  1961. self.figs = est
  1962. self.scores_.append(mean_score)
  1963. self.figs.fit(X=X, y=y)</code></pre>
  1964. </details>
  1965. </dd>
  1966. <dt id="imodels.tree.figs.FIGSCV.predict"><code class="name flex">
  1967. <span>def <span class="ident">predict</span></span>(<span>self, X)</span>
  1968. </code></dt>
  1969. <dd>
  1970. <div class="desc"></div>
  1971. <details class="source">
  1972. <summary>
  1973. <span>Expand source code</span>
  1974. </summary>
  1975. <pre><code class="python">def predict(self, X):
  1976. return self.figs.predict(X)</code></pre>
  1977. </details>
  1978. </dd>
  1979. <dt id="imodels.tree.figs.FIGSCV.predict_proba"><code class="name flex">
  1980. <span>def <span class="ident">predict_proba</span></span>(<span>self, X)</span>
  1981. </code></dt>
  1982. <dd>
  1983. <div class="desc"></div>
  1984. <details class="source">
  1985. <summary>
  1986. <span>Expand source code</span>
  1987. </summary>
  1988. <pre><code class="python">def predict_proba(self, X):
  1989. return self.figs.predict_proba(X)</code></pre>
  1990. </details>
  1991. </dd>
  1992. </dl>
  1993. </dd>
  1994. <dt id="imodels.tree.figs.FIGSClassifier"><code class="flex name class">
  1995. <span>class <span class="ident">FIGSClassifier</span></span>
  1996. <span>(</span><span>max_rules: int = 12, max_trees: int = None, min_impurity_decrease: float = 0.0, random_state=None, max_features: str = None)</span>
  1997. </code></dt>
  1998. <dd>
  1999. <div class="desc"><p>FIGS (sum of trees) classifier.
  2000. Fast Interpretable Greedy-Tree Sums (FIGS) is an algorithm for fitting concise rule-based models.
  2001. Specifically, FIGS generalizes CART to simultaneously grow a flexible number of trees in a summation.
  2002. The total number of splits across all the trees can be restricted by a pre-specified threshold, keeping the model interpretable.
  2003. Experiments across real-world datasets show that FIGS achieves state-of-the-art prediction performance when restricted to just a few splits (e.g. less than 20).
  2004. <a href="https://arxiv.org/abs/2201.11931">https://arxiv.org/abs/2201.11931</a></p>
  2005. <h2 id="params">Params</h2>
  2006. <p>max_rules: int
  2007. Max total number of rules across all trees
  2008. max_trees: int
  2009. Max total number of trees
  2010. min_impurity_decrease: float
  2011. A node will be split if this split induces a decrease of the impurity greater than or equal to this value.
  2012. max_features
  2013. The number of features to consider when looking for the best split (see <a href="https://scikit-learn.org/stable/modules/generated/sklearn.ensemble.RandomForestClassifier.html">https://scikit-learn.org/stable/modules/generated/sklearn.ensemble.RandomForestClassifier.html</a>)</p></div>
  2014. <details class="source">
  2015. <summary>
  2016. <span>Expand source code</span>
  2017. </summary>
  2018. <pre><code class="python">class FIGSClassifier(FIGS, ClassifierMixin):
  2019. ...</code></pre>
  2020. </details>
  2021. <h3>Ancestors</h3>
  2022. <ul class="hlist">
  2023. <li><a title="imodels.tree.figs.FIGS" href="#imodels.tree.figs.FIGS">FIGS</a></li>
  2024. <li>sklearn.base.BaseEstimator</li>
  2025. <li>sklearn.utils._estimator_html_repr._HTMLDocumentationLinkMixin</li>
  2026. <li>sklearn.utils._metadata_requests._MetadataRequester</li>
  2027. <li>sklearn.base.ClassifierMixin</li>
  2028. </ul>
  2029. <h3>Methods</h3>
  2030. <dl>
  2031. <dt id="imodels.tree.figs.FIGSClassifier.set_score_request"><code class="name flex">
  2032. <span>def <span class="ident">set_score_request</span></span>(<span>self: <a title="imodels.tree.figs.FIGSClassifier" href="#imodels.tree.figs.FIGSClassifier">FIGSClassifier</a>, *, sample_weight: Union[bool, ForwardRef(None), str] = '$UNCHANGED$') ‑> <a title="imodels.tree.figs.FIGSClassifier" href="#imodels.tree.figs.FIGSClassifier">FIGSClassifier</a></span>
  2033. </code></dt>
  2034. <dd>
  2035. <div class="desc"><p>Request metadata passed to the <code>score</code> method.</p>
  2036. <p>Note that this method is only relevant if
  2037. <code>enable_metadata_routing=True</code> (see :func:<code>sklearn.set_config</code>).
  2038. Please see :ref:<code>User Guide &lt;metadata_routing&gt;</code> on how the routing
  2039. mechanism works.</p>
  2040. <p>The options for each parameter are:</p>
  2041. <ul>
  2042. <li>
  2043. <p><code>True</code>: metadata is requested, and passed to <code>score</code> if provided. The request is ignored if metadata is not provided.</p>
  2044. </li>
  2045. <li>
  2046. <p><code>False</code>: metadata is not requested and the meta-estimator will not pass it to <code>score</code>.</p>
  2047. </li>
  2048. <li>
  2049. <p><code>None</code>: metadata is not requested, and the meta-estimator will raise an error if the user provides it.</p>
  2050. </li>
  2051. <li>
  2052. <p><code>str</code>: metadata should be passed to the meta-estimator with this given alias instead of the original name.</p>
  2053. </li>
  2054. </ul>
  2055. <p>The default (<code>sklearn.utils.metadata_routing.UNCHANGED</code>) retains the
  2056. existing request. This allows you to change the request for some
  2057. parameters and not others.</p>
  2058. <div class="admonition versionadded">
  2059. <p class="admonition-title">Added in version:&ensp;1.3</p>
  2060. </div>
  2061. <div class="admonition note">
  2062. <p class="admonition-title">Note</p>
  2063. <p>This method is only relevant if this estimator is used as a
  2064. sub-estimator of a meta-estimator, e.g. used inside a
  2065. :class:<code>~sklearn.pipeline.Pipeline</code>. Otherwise it has no effect.</p>
  2066. </div>
  2067. <h2 id="parameters">Parameters</h2>
  2068. <dl>
  2069. <dt><strong><code>sample_weight</code></strong> :&ensp;<code>str, True, False,</code> or <code>None</code>,
  2070. default=<code>sklearn.utils.metadata_routing.UNCHANGED</code></dt>
  2071. <dd>Metadata routing for <code>sample_weight</code> parameter in <code>score</code>.</dd>
  2072. </dl>
  2073. <h2 id="returns">Returns</h2>
  2074. <dl>
  2075. <dt><strong><code>self</code></strong> :&ensp;<code>object</code></dt>
  2076. <dd>The updated object.</dd>
  2077. </dl></div>
  2078. <details class="source">
  2079. <summary>
  2080. <span>Expand source code</span>
  2081. </summary>
  2082. <pre><code class="python">def func(**kw):
  2083. &#34;&#34;&#34;Updates the request for provided parameters
  2084. This docstring is overwritten below.
  2085. See REQUESTER_DOC for expected functionality
  2086. &#34;&#34;&#34;
  2087. if not _routing_enabled():
  2088. raise RuntimeError(
  2089. &#34;This method is only available when metadata routing is enabled.&#34;
  2090. &#34; You can enable it using&#34;
  2091. &#34; sklearn.set_config(enable_metadata_routing=True).&#34;
  2092. )
  2093. if self.validate_keys and (set(kw) - set(self.keys)):
  2094. raise TypeError(
  2095. f&#34;Unexpected args: {set(kw) - set(self.keys)}. Accepted arguments&#34;
  2096. f&#34; are: {set(self.keys)}&#34;
  2097. )
  2098. requests = instance._get_metadata_request()
  2099. method_metadata_request = getattr(requests, self.name)
  2100. for prop, alias in kw.items():
  2101. if alias is not UNCHANGED:
  2102. method_metadata_request.add_request(param=prop, alias=alias)
  2103. instance._metadata_request = requests
  2104. return instance</code></pre>
  2105. </details>
  2106. </dd>
  2107. </dl>
  2108. <h3>Inherited members</h3>
  2109. <ul class="hlist">
  2110. <li><code><b><a title="imodels.tree.figs.FIGS" href="#imodels.tree.figs.FIGS">FIGS</a></b></code>:
  2111. <ul class="hlist">
  2112. <li><code><a title="imodels.tree.figs.FIGS.feature_importances_" href="#imodels.tree.figs.FIGS.feature_importances_">feature_importances_</a></code></li>
  2113. <li><code><a title="imodels.tree.figs.FIGS.fit" href="#imodels.tree.figs.FIGS.fit">fit</a></code></li>
  2114. <li><code><a title="imodels.tree.figs.FIGS.predict_proba" href="#imodels.tree.figs.FIGS.predict_proba">predict_proba</a></code></li>
  2115. <li><code><a title="imodels.tree.figs.FIGS.set_fit_request" href="#imodels.tree.figs.FIGS.set_fit_request">set_fit_request</a></code></li>
  2116. <li><code><a title="imodels.tree.figs.FIGS.set_predict_proba_request" href="#imodels.tree.figs.FIGS.set_predict_proba_request">set_predict_proba_request</a></code></li>
  2117. <li><code><a title="imodels.tree.figs.FIGS.set_predict_request" href="#imodels.tree.figs.FIGS.set_predict_request">set_predict_request</a></code></li>
  2118. </ul>
  2119. </li>
  2120. </ul>
  2121. </dd>
  2122. <dt id="imodels.tree.figs.FIGSClassifierCV"><code class="flex name class">
  2123. <span>class <span class="ident">FIGSClassifierCV</span></span>
  2124. <span>(</span><span>n_rules_list: List[int] = [6, 12, 24, 30, 50], n_trees_list: List[int] = [5, 5, 5, 5, 5], cv: int = 3, scoring='accuracy', *args, **kwargs)</span>
  2125. </code></dt>
  2126. <dd>
  2127. <div class="desc"></div>
  2128. <details class="source">
  2129. <summary>
  2130. <span>Expand source code</span>
  2131. </summary>
  2132. <pre><code class="python">class FIGSClassifierCV(FIGSCV):
  2133. def __init__(
  2134. self,
  2135. n_rules_list: List[int] = [6, 12, 24, 30, 50],
  2136. n_trees_list: List[int] = [5, 5, 5, 5, 5],
  2137. cv: int = 3,
  2138. scoring=&#34;accuracy&#34;,
  2139. *args,
  2140. **kwargs,
  2141. ):
  2142. super(FIGSClassifierCV, self).__init__(
  2143. figs=FIGSClassifier,
  2144. n_rules_list=n_rules_list,
  2145. n_trees_list=n_trees_list,
  2146. cv=cv,
  2147. scoring=scoring,
  2148. *args,
  2149. **kwargs,
  2150. )</code></pre>
  2151. </details>
  2152. <h3>Ancestors</h3>
  2153. <ul class="hlist">
  2154. <li><a title="imodels.tree.figs.FIGSCV" href="#imodels.tree.figs.FIGSCV">FIGSCV</a></li>
  2155. </ul>
  2156. </dd>
  2157. <dt id="imodels.tree.figs.FIGSRegressor"><code class="flex name class">
  2158. <span>class <span class="ident">FIGSRegressor</span></span>
  2159. <span>(</span><span>max_rules: int = 12, max_trees: int = None, min_impurity_decrease: float = 0.0, random_state=None, max_features: str = None)</span>
  2160. </code></dt>
  2161. <dd>
  2162. <div class="desc"><p>FIGS (sum of trees) classifier.
  2163. Fast Interpretable Greedy-Tree Sums (FIGS) is an algorithm for fitting concise rule-based models.
  2164. Specifically, FIGS generalizes CART to simultaneously grow a flexible number of trees in a summation.
  2165. The total number of splits across all the trees can be restricted by a pre-specified threshold, keeping the model interpretable.
  2166. Experiments across real-world datasets show that FIGS achieves state-of-the-art prediction performance when restricted to just a few splits (e.g. less than 20).
  2167. <a href="https://arxiv.org/abs/2201.11931">https://arxiv.org/abs/2201.11931</a></p>
  2168. <h2 id="params">Params</h2>
  2169. <p>max_rules: int
  2170. Max total number of rules across all trees
  2171. max_trees: int
  2172. Max total number of trees
  2173. min_impurity_decrease: float
  2174. A node will be split if this split induces a decrease of the impurity greater than or equal to this value.
  2175. max_features
  2176. The number of features to consider when looking for the best split (see <a href="https://scikit-learn.org/stable/modules/generated/sklearn.ensemble.RandomForestClassifier.html">https://scikit-learn.org/stable/modules/generated/sklearn.ensemble.RandomForestClassifier.html</a>)</p></div>
  2177. <details class="source">
  2178. <summary>
  2179. <span>Expand source code</span>
  2180. </summary>
  2181. <pre><code class="python">class FIGSRegressor(FIGS, RegressorMixin):
  2182. ...</code></pre>
  2183. </details>
  2184. <h3>Ancestors</h3>
  2185. <ul class="hlist">
  2186. <li><a title="imodels.tree.figs.FIGS" href="#imodels.tree.figs.FIGS">FIGS</a></li>
  2187. <li>sklearn.base.BaseEstimator</li>
  2188. <li>sklearn.utils._estimator_html_repr._HTMLDocumentationLinkMixin</li>
  2189. <li>sklearn.utils._metadata_requests._MetadataRequester</li>
  2190. <li>sklearn.base.RegressorMixin</li>
  2191. </ul>
  2192. <h3>Methods</h3>
  2193. <dl>
  2194. <dt id="imodels.tree.figs.FIGSRegressor.set_score_request"><code class="name flex">
  2195. <span>def <span class="ident">set_score_request</span></span>(<span>self: <a title="imodels.tree.figs.FIGSRegressor" href="#imodels.tree.figs.FIGSRegressor">FIGSRegressor</a>, *, sample_weight: Union[bool, ForwardRef(None), str] = '$UNCHANGED$') ‑> <a title="imodels.tree.figs.FIGSRegressor" href="#imodels.tree.figs.FIGSRegressor">FIGSRegressor</a></span>
  2196. </code></dt>
  2197. <dd>
  2198. <div class="desc"><p>Request metadata passed to the <code>score</code> method.</p>
  2199. <p>Note that this method is only relevant if
  2200. <code>enable_metadata_routing=True</code> (see :func:<code>sklearn.set_config</code>).
  2201. Please see :ref:<code>User Guide &lt;metadata_routing&gt;</code> on how the routing
  2202. mechanism works.</p>
  2203. <p>The options for each parameter are:</p>
  2204. <ul>
  2205. <li>
  2206. <p><code>True</code>: metadata is requested, and passed to <code>score</code> if provided. The request is ignored if metadata is not provided.</p>
  2207. </li>
  2208. <li>
  2209. <p><code>False</code>: metadata is not requested and the meta-estimator will not pass it to <code>score</code>.</p>
  2210. </li>
  2211. <li>
  2212. <p><code>None</code>: metadata is not requested, and the meta-estimator will raise an error if the user provides it.</p>
  2213. </li>
  2214. <li>
  2215. <p><code>str</code>: metadata should be passed to the meta-estimator with this given alias instead of the original name.</p>
  2216. </li>
  2217. </ul>
  2218. <p>The default (<code>sklearn.utils.metadata_routing.UNCHANGED</code>) retains the
  2219. existing request. This allows you to change the request for some
  2220. parameters and not others.</p>
  2221. <div class="admonition versionadded">
  2222. <p class="admonition-title">Added in version:&ensp;1.3</p>
  2223. </div>
  2224. <div class="admonition note">
  2225. <p class="admonition-title">Note</p>
  2226. <p>This method is only relevant if this estimator is used as a
  2227. sub-estimator of a meta-estimator, e.g. used inside a
  2228. :class:<code>~sklearn.pipeline.Pipeline</code>. Otherwise it has no effect.</p>
  2229. </div>
  2230. <h2 id="parameters">Parameters</h2>
  2231. <dl>
  2232. <dt><strong><code>sample_weight</code></strong> :&ensp;<code>str, True, False,</code> or <code>None</code>,
  2233. default=<code>sklearn.utils.metadata_routing.UNCHANGED</code></dt>
  2234. <dd>Metadata routing for <code>sample_weight</code> parameter in <code>score</code>.</dd>
  2235. </dl>
  2236. <h2 id="returns">Returns</h2>
  2237. <dl>
  2238. <dt><strong><code>self</code></strong> :&ensp;<code>object</code></dt>
  2239. <dd>The updated object.</dd>
  2240. </dl></div>
  2241. <details class="source">
  2242. <summary>
  2243. <span>Expand source code</span>
  2244. </summary>
  2245. <pre><code class="python">def func(**kw):
  2246. &#34;&#34;&#34;Updates the request for provided parameters
  2247. This docstring is overwritten below.
  2248. See REQUESTER_DOC for expected functionality
  2249. &#34;&#34;&#34;
  2250. if not _routing_enabled():
  2251. raise RuntimeError(
  2252. &#34;This method is only available when metadata routing is enabled.&#34;
  2253. &#34; You can enable it using&#34;
  2254. &#34; sklearn.set_config(enable_metadata_routing=True).&#34;
  2255. )
  2256. if self.validate_keys and (set(kw) - set(self.keys)):
  2257. raise TypeError(
  2258. f&#34;Unexpected args: {set(kw) - set(self.keys)}. Accepted arguments&#34;
  2259. f&#34; are: {set(self.keys)}&#34;
  2260. )
  2261. requests = instance._get_metadata_request()
  2262. method_metadata_request = getattr(requests, self.name)
  2263. for prop, alias in kw.items():
  2264. if alias is not UNCHANGED:
  2265. method_metadata_request.add_request(param=prop, alias=alias)
  2266. instance._metadata_request = requests
  2267. return instance</code></pre>
  2268. </details>
  2269. </dd>
  2270. </dl>
  2271. <h3>Inherited members</h3>
  2272. <ul class="hlist">
  2273. <li><code><b><a title="imodels.tree.figs.FIGS" href="#imodels.tree.figs.FIGS">FIGS</a></b></code>:
  2274. <ul class="hlist">
  2275. <li><code><a title="imodels.tree.figs.FIGS.feature_importances_" href="#imodels.tree.figs.FIGS.feature_importances_">feature_importances_</a></code></li>
  2276. <li><code><a title="imodels.tree.figs.FIGS.fit" href="#imodels.tree.figs.FIGS.fit">fit</a></code></li>
  2277. <li><code><a title="imodels.tree.figs.FIGS.predict_proba" href="#imodels.tree.figs.FIGS.predict_proba">predict_proba</a></code></li>
  2278. <li><code><a title="imodels.tree.figs.FIGS.set_fit_request" href="#imodels.tree.figs.FIGS.set_fit_request">set_fit_request</a></code></li>
  2279. <li><code><a title="imodels.tree.figs.FIGS.set_predict_proba_request" href="#imodels.tree.figs.FIGS.set_predict_proba_request">set_predict_proba_request</a></code></li>
  2280. <li><code><a title="imodels.tree.figs.FIGS.set_predict_request" href="#imodels.tree.figs.FIGS.set_predict_request">set_predict_request</a></code></li>
  2281. </ul>
  2282. </li>
  2283. </ul>
  2284. </dd>
  2285. <dt id="imodels.tree.figs.FIGSRegressorCV"><code class="flex name class">
  2286. <span>class <span class="ident">FIGSRegressorCV</span></span>
  2287. <span>(</span><span>n_rules_list: List[int] = [6, 12, 24, 30, 50], n_trees_list: List[int] = [5, 5, 5, 5, 5], cv: int = 3, scoring='r2', *args, **kwargs)</span>
  2288. </code></dt>
  2289. <dd>
  2290. <div class="desc"></div>
  2291. <details class="source">
  2292. <summary>
  2293. <span>Expand source code</span>
  2294. </summary>
  2295. <pre><code class="python">class FIGSRegressorCV(FIGSCV):
  2296. def __init__(
  2297. self,
  2298. n_rules_list: List[int] = [6, 12, 24, 30, 50],
  2299. n_trees_list: List[int] = [5, 5, 5, 5, 5],
  2300. cv: int = 3,
  2301. scoring=&#34;r2&#34;,
  2302. *args,
  2303. **kwargs,
  2304. ):
  2305. super(FIGSRegressorCV, self).__init__(
  2306. figs=FIGSRegressor,
  2307. n_rules_list=n_rules_list,
  2308. n_trees_list=n_trees_list,
  2309. cv=cv,
  2310. scoring=scoring,
  2311. *args,
  2312. **kwargs,
  2313. )</code></pre>
  2314. </details>
  2315. <h3>Ancestors</h3>
  2316. <ul class="hlist">
  2317. <li><a title="imodels.tree.figs.FIGSCV" href="#imodels.tree.figs.FIGSCV">FIGSCV</a></li>
  2318. </ul>
  2319. </dd>
  2320. <dt id="imodels.tree.figs.Node"><code class="flex name class">
  2321. <span>class <span class="ident">Node</span></span>
  2322. <span>(</span><span>feature: int = None, threshold: int = None, value=None, value_sklearn=None, idxs=None, is_root: bool = False, left=None, impurity: float = None, impurity_reduction: float = None, tree_num: int = None, node_id: int = None, right=None)</span>
  2323. </code></dt>
  2324. <dd>
  2325. <div class="desc"><p>Node class for splitting</p></div>
  2326. <details class="source">
  2327. <summary>
  2328. <span>Expand source code</span>
  2329. </summary>
  2330. <pre><code class="python">class Node:
  2331. def __init__(
  2332. self,
  2333. feature: int = None,
  2334. threshold: int = None,
  2335. value=None,
  2336. value_sklearn=None,
  2337. idxs=None,
  2338. is_root: bool = False,
  2339. left=None,
  2340. impurity: float = None,
  2341. impurity_reduction: float = None,
  2342. tree_num: int = None,
  2343. node_id: int = None,
  2344. right=None,
  2345. ):
  2346. &#34;&#34;&#34;Node class for splitting&#34;&#34;&#34;
  2347. # split or linear
  2348. self.is_root = is_root
  2349. self.idxs = idxs
  2350. self.tree_num = tree_num
  2351. self.node_id = None
  2352. self.feature = feature
  2353. self.impurity = impurity
  2354. self.impurity_reduction = impurity_reduction
  2355. self.value_sklearn = value_sklearn
  2356. # different meanings
  2357. self.value = value # for split this is mean, for linear this is weight
  2358. # split-specific
  2359. self.threshold = threshold
  2360. self.left = left
  2361. self.right = right
  2362. self.left_temp = None
  2363. self.right_temp = None
  2364. def setattrs(self, **kwargs):
  2365. for k, v in kwargs.items():
  2366. setattr(self, k, v)
  2367. def __str__(self):
  2368. if self.is_root:
  2369. return f&#34;X_{self.feature} &lt;= {self.threshold:0.3f} (Tree #{self.tree_num} root)&#34;
  2370. elif self.left is None and self.right is None:
  2371. return f&#34;Val: {self.value[0][0]:0.3f} (leaf)&#34;
  2372. else:
  2373. return f&#34;X_{self.feature} &lt;= {self.threshold:0.3f} (split)&#34;
  2374. def print_root(self, y):
  2375. try:
  2376. one_count = pd.Series(y).value_counts()[1.0]
  2377. except KeyError:
  2378. one_count = 0
  2379. one_proportion = (
  2380. f&#34; {one_count}/{y.shape[0]} ({round(100 * one_count / y.shape[0], 2)}%)&#34;
  2381. )
  2382. if self.is_root:
  2383. return f&#34;X_{self.feature} &lt;= {self.threshold:0.3f}&#34; + one_proportion
  2384. elif self.left is None and self.right is None:
  2385. return f&#34;ΔRisk = {self.value[0][0]:0.2f}&#34; + one_proportion
  2386. else:
  2387. return f&#34;X_{self.feature} &lt;= {self.threshold:0.3f}&#34; + one_proportion
  2388. def __repr__(self):
  2389. return self.__str__()</code></pre>
  2390. </details>
  2391. <h3>Methods</h3>
  2392. <dl>
  2393. <dt id="imodels.tree.figs.Node.print_root"><code class="name flex">
  2394. <span>def <span class="ident">print_root</span></span>(<span>self, y)</span>
  2395. </code></dt>
  2396. <dd>
  2397. <div class="desc"></div>
  2398. <details class="source">
  2399. <summary>
  2400. <span>Expand source code</span>
  2401. </summary>
  2402. <pre><code class="python">def print_root(self, y):
  2403. try:
  2404. one_count = pd.Series(y).value_counts()[1.0]
  2405. except KeyError:
  2406. one_count = 0
  2407. one_proportion = (
  2408. f&#34; {one_count}/{y.shape[0]} ({round(100 * one_count / y.shape[0], 2)}%)&#34;
  2409. )
  2410. if self.is_root:
  2411. return f&#34;X_{self.feature} &lt;= {self.threshold:0.3f}&#34; + one_proportion
  2412. elif self.left is None and self.right is None:
  2413. return f&#34;ΔRisk = {self.value[0][0]:0.2f}&#34; + one_proportion
  2414. else:
  2415. return f&#34;X_{self.feature} &lt;= {self.threshold:0.3f}&#34; + one_proportion</code></pre>
  2416. </details>
  2417. </dd>
  2418. <dt id="imodels.tree.figs.Node.setattrs"><code class="name flex">
  2419. <span>def <span class="ident">setattrs</span></span>(<span>self, **kwargs)</span>
  2420. </code></dt>
  2421. <dd>
  2422. <div class="desc"></div>
  2423. <details class="source">
  2424. <summary>
  2425. <span>Expand source code</span>
  2426. </summary>
  2427. <pre><code class="python">def setattrs(self, **kwargs):
  2428. for k, v in kwargs.items():
  2429. setattr(self, k, v)</code></pre>
  2430. </details>
  2431. </dd>
  2432. </dl>
  2433. </dd>
  2434. </dl>
  2435. </section>
  2436. </article>
  2437. <nav id="sidebar">
  2438. <h1>Index 🔍</h1>
  2439. <div class="toc">
  2440. <ul></ul>
  2441. </div>
  2442. <ul id="index">
  2443. <li><h3>Super-module</h3>
  2444. <ul>
  2445. <li><code><a title="imodels.tree" href="index.html">imodels.tree</a></code></li>
  2446. </ul>
  2447. </li>
  2448. <li><h3><a href="#header-classes">Classes</a></h3>
  2449. <ul>
  2450. <li>
  2451. <h4><code><a title="imodels.tree.figs.FIGS" href="#imodels.tree.figs.FIGS">FIGS</a></code></h4>
  2452. <ul class="">
  2453. <li><code><a title="imodels.tree.figs.FIGS.feature_importances_" href="#imodels.tree.figs.FIGS.feature_importances_">feature_importances_</a></code></li>
  2454. <li><code><a title="imodels.tree.figs.FIGS.fit" href="#imodels.tree.figs.FIGS.fit">fit</a></code></li>
  2455. <li><code><a title="imodels.tree.figs.FIGS.plot" href="#imodels.tree.figs.FIGS.plot">plot</a></code></li>
  2456. <li><code><a title="imodels.tree.figs.FIGS.predict" href="#imodels.tree.figs.FIGS.predict">predict</a></code></li>
  2457. <li><code><a title="imodels.tree.figs.FIGS.predict_proba" href="#imodels.tree.figs.FIGS.predict_proba">predict_proba</a></code></li>
  2458. <li><code><a title="imodels.tree.figs.FIGS.print_tree" href="#imodels.tree.figs.FIGS.print_tree">print_tree</a></code></li>
  2459. <li><code><a title="imodels.tree.figs.FIGS.set_fit_request" href="#imodels.tree.figs.FIGS.set_fit_request">set_fit_request</a></code></li>
  2460. <li><code><a title="imodels.tree.figs.FIGS.set_predict_proba_request" href="#imodels.tree.figs.FIGS.set_predict_proba_request">set_predict_proba_request</a></code></li>
  2461. <li><code><a title="imodels.tree.figs.FIGS.set_predict_request" href="#imodels.tree.figs.FIGS.set_predict_request">set_predict_request</a></code></li>
  2462. </ul>
  2463. </li>
  2464. <li>
  2465. <h4><code><a title="imodels.tree.figs.FIGSCV" href="#imodels.tree.figs.FIGSCV">FIGSCV</a></code></h4>
  2466. <ul class="">
  2467. <li><code><a title="imodels.tree.figs.FIGSCV.fit" href="#imodels.tree.figs.FIGSCV.fit">fit</a></code></li>
  2468. <li><code><a title="imodels.tree.figs.FIGSCV.max_rules" href="#imodels.tree.figs.FIGSCV.max_rules">max_rules</a></code></li>
  2469. <li><code><a title="imodels.tree.figs.FIGSCV.max_trees" href="#imodels.tree.figs.FIGSCV.max_trees">max_trees</a></code></li>
  2470. <li><code><a title="imodels.tree.figs.FIGSCV.predict" href="#imodels.tree.figs.FIGSCV.predict">predict</a></code></li>
  2471. <li><code><a title="imodels.tree.figs.FIGSCV.predict_proba" href="#imodels.tree.figs.FIGSCV.predict_proba">predict_proba</a></code></li>
  2472. </ul>
  2473. </li>
  2474. <li>
  2475. <h4><code><a title="imodels.tree.figs.FIGSClassifier" href="#imodels.tree.figs.FIGSClassifier">FIGSClassifier</a></code></h4>
  2476. <ul class="">
  2477. <li><code><a title="imodels.tree.figs.FIGSClassifier.set_score_request" href="#imodels.tree.figs.FIGSClassifier.set_score_request">set_score_request</a></code></li>
  2478. </ul>
  2479. </li>
  2480. <li>
  2481. <h4><code><a title="imodels.tree.figs.FIGSClassifierCV" href="#imodels.tree.figs.FIGSClassifierCV">FIGSClassifierCV</a></code></h4>
  2482. </li>
  2483. <li>
  2484. <h4><code><a title="imodels.tree.figs.FIGSRegressor" href="#imodels.tree.figs.FIGSRegressor">FIGSRegressor</a></code></h4>
  2485. <ul class="">
  2486. <li><code><a title="imodels.tree.figs.FIGSRegressor.set_score_request" href="#imodels.tree.figs.FIGSRegressor.set_score_request">set_score_request</a></code></li>
  2487. </ul>
  2488. </li>
  2489. <li>
  2490. <h4><code><a title="imodels.tree.figs.FIGSRegressorCV" href="#imodels.tree.figs.FIGSRegressorCV">FIGSRegressorCV</a></code></h4>
  2491. </li>
  2492. <li>
  2493. <h4><code><a title="imodels.tree.figs.Node" href="#imodels.tree.figs.Node">Node</a></code></h4>
  2494. <ul class="">
  2495. <li><code><a title="imodels.tree.figs.Node.print_root" href="#imodels.tree.figs.Node.print_root">print_root</a></code></li>
  2496. <li><code><a title="imodels.tree.figs.Node.setattrs" href="#imodels.tree.figs.Node.setattrs">setattrs</a></code></li>
  2497. </ul>
  2498. </li>
  2499. </ul>
  2500. </li>
  2501. </ul>
  2502. <p><img align="center" width=100% src="https://csinva.io/imodels/img/anim.gif"> </img></p>
  2503. <!-- add wave animation -->
  2504. </nav>
  2505. </main>
  2506. <footer id="footer">
  2507. </footer>
  2508. </body>
  2509. </html>
  2510. <!-- add github corner -->
  2511. <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>
  2512. <!-- add wave animation stylesheet -->
  2513. <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...