Core Classes¶
Source code in src/pytorch_tabular/tabular_model.py
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 |
|
__init__(config=None, data_config=None, model_config=None, optimizer_config=None, trainer_config=None, experiment_config=None, model_callable=None, model_state_dict_path=None, verbose=True, suppress_lightning_logger=False)
¶
The core model which orchestrates everything from initializing the datamodule, the model, trainer, etc.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
config |
Optional[Union[DictConfig, str]]
|
Single OmegaConf DictConfig object or the path to the yaml file holding all the config parameters. Defaults to None. |
None
|
data_config |
Optional[Union[DataConfig, str]]
|
DataConfig object or path to the yaml file. Defaults to None. |
None
|
model_config |
Optional[Union[ModelConfig, str]]
|
A subclass of ModelConfig or path to the yaml file. Determines which model to run from the type of config. Defaults to None. |
None
|
optimizer_config |
Optional[Union[OptimizerConfig, str]]
|
OptimizerConfig object or path to the yaml file. Defaults to None. |
None
|
trainer_config |
Optional[Union[TrainerConfig, str]]
|
TrainerConfig object or path to the yaml file. Defaults to None. |
None
|
experiment_config |
Optional[Union[ExperimentConfig, str]]
|
ExperimentConfig object or path to the yaml file. If Provided configures the experiment tracking. Defaults to None. |
None
|
model_callable |
Optional[Callable]
|
If provided, will override the model callable that will be loaded from the config. Typically used when providing Custom Models |
None
|
model_state_dict_path |
Optional[Union[str, Path]]
|
If provided, will load the state dict after initializing the model from config. |
None
|
verbose |
bool
|
turns off and on the logging. Defaults to True. |
True
|
suppress_lightning_logger |
bool
|
If True, will suppress the default logging from PyTorch Lightning. Defaults to False. |
False
|
Source code in src/pytorch_tabular/tabular_model.py
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 |
|
bagging_predict(cv, train, test, groups=None, verbose=True, reset_datamodule=True, return_raw_predictions=False, aggregate='mean', weights=None, handle_oom=True, **kwargs)
¶
Bagging predict on the test data.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
cv |
Optional[Union[int, Iterable, BaseCrossValidator]]
|
Determines the cross-validation splitting strategy. Possible inputs for cv are:
|
required |
train |
DataFrame
|
The training data with labels |
required |
test |
DataFrame
|
The test data to be predicted |
required |
groups |
Optional[Union[str, ndarray]]
|
Group labels for
the samples used while splitting. If provided, will be used as the
|
None
|
verbose |
bool
|
If True, will log the results. Defaults to True. |
True
|
reset_datamodule |
bool
|
If True, will reset the datamodule for each iteration. It will be slower because we will be fitting the transformations for each fold. If False, we take an approximation that once the transformations are fit on the first fold, they will be valid for all the other folds. Defaults to True. |
True
|
return_raw_predictions |
bool
|
If True, will return the raw predictions from each fold. Defaults to False. |
False
|
aggregate |
Union[str, Callable]
|
The function to be used to aggregate the predictions from each fold. If str, should be one of "mean", "median", "min", or "max" for regression. For classification, the previous options are applied to the confidence scores (soft voting) and then converted to final prediction. An additional option "hard_voting" is available for classification. If callable, should be a function that takes in a list of 3D arrays (num_samples, num_cv, num_targets) and returns a 2D array of final probabilities (num_samples, num_targets). Defaults to "mean". |
'mean'
|
weights |
Optional[List[float]]
|
The weights to be used for aggregating the predictions
from each fold. If None, will use equal weights. This is only used when |
None
|
handle_oom |
bool
|
If True, will handle out of memory errors elegantly |
True
|
**kwargs |
Additional keyword arguments to be passed to the |
{}
|
Returns:
Name | Type | Description |
---|---|---|
DataFrame |
The dataframe with the bagged predictions. |
Source code in src/pytorch_tabular/tabular_model.py
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 |
|
create_finetune_model(task, head, head_config, train, validation=None, train_sampler=None, target_transform=None, target=None, optimizer_config=None, trainer_config=None, experiment_config=None, loss=None, metrics=None, metrics_prob_input=None, metrics_params=None, optimizer=None, optimizer_params=None, learning_rate=None, target_range=None, seed=42)
¶
Creates a new TabularModel model using the pretrained weights and the new task and head.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
task |
str
|
The task to be performed. One of "regression", "classification" |
required |
head |
str
|
The head to be used for the model. Should be one of the heads defined
in |
required |
head_config |
Dict
|
The config as a dict which defines the head. If left empty, will be initialized as default linear head. |
required |
train |
DataFrame
|
The training data with labels |
required |
validation |
Optional[DataFrame]
|
The validation data with labels. Defaults to None. |
None
|
train_sampler |
Optional[Sampler]
|
If provided, will be used as a batch sampler for training. Defaults to None. |
None
|
target_transform |
Optional[Union[TransformerMixin, Tuple]]
|
If provided, will be used to transform the target before training and inverse transform the predictions. |
None
|
target |
Optional[str]
|
The target column name if not provided in the initial pretraining stage. Defaults to None. |
None
|
optimizer_config |
Optional[OptimizerConfig]
|
If provided, will redefine the optimizer for fine-tuning stage. Defaults to None. |
None
|
trainer_config |
Optional[TrainerConfig]
|
If provided, will redefine the trainer for fine-tuning stage. Defaults to None. |
None
|
experiment_config |
Optional[ExperimentConfig]
|
If provided, will redefine the experiment for fine-tuning stage. Defaults to None. |
None
|
loss |
Optional[Module]
|
If provided, will be used as the loss function for the fine-tuning. By default, it is MSELoss for regression and CrossEntropyLoss for classification. |
None
|
metrics |
Optional[List[Callable]]
|
List of metrics (either callables or str) to be used for the
fine-tuning stage. If str, it should be one of the functional metrics implemented in
|
None
|
metrics_prob_input |
Optional[List[bool]]
|
Is a mandatory parameter for classification metrics This defines whether the input to the metric function is the probability or the class. Length should be same as the number of metrics. Defaults to None. |
None
|
metrics_params |
Optional[Dict]
|
The parameters for the metrics in the same order as metrics.
For eg. f1_score for multi-class needs a parameter |
None
|
optimizer |
Optional[Optimizer]
|
Custom optimizers which are a drop in replacements for standard PyTorch optimizers. If provided, the OptimizerConfig is ignored in favor of this. Defaults to None. |
None
|
optimizer_params |
Dict
|
The parameters for the optimizer. Defaults to {}. |
None
|
learning_rate |
Optional[float]
|
The learning rate to be used. Defaults to 1e-3. |
None
|
target_range |
Optional[Tuple[float, float]]
|
The target range for the regression task. Is ignored for classification. Defaults to None. |
None
|
seed |
Optional[int]
|
Random seed for reproducibility. Defaults to 42. |
42
|
Returns: TabularModel (TabularModel): The new TabularModel model for fine-tuning
Source code in src/pytorch_tabular/tabular_model.py
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 |
|
cross_validate(cv, train, metric=None, return_oof=False, groups=None, verbose=True, reset_datamodule=True, handle_oom=True, **kwargs)
¶
Cross validate the model.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
cv |
Optional[Union[int, Iterable, BaseCrossValidator]]
|
Determines the cross-validation splitting strategy. Possible inputs for cv are:
|
required |
train |
DataFrame
|
The training data with labels |
required |
metric |
Optional[Union[str, Callable]]
|
The metrics to be used for evaluation.
If None, will use the first metric in the config. If str is provided, will use that
metric from the defined ones. If callable is provided, will use that function as the
metric. We expect callable to be of the form |
None
|
return_oof |
bool
|
If True, will return the out-of-fold predictions along with the cross validation results. Defaults to False. |
False
|
groups |
Optional[Union[str, ndarray]]
|
Group labels for
the samples used while splitting. If provided, will be used as the
|
None
|
verbose |
bool
|
If True, will log the results. Defaults to True. |
True
|
reset_datamodule |
bool
|
If True, will reset the datamodule for each iteration. It will be slower because we will be fitting the transformations for each fold. If False, we take an approximation that once the transformations are fit on the first fold, they will be valid for all the other folds. Defaults to True. |
True
|
handle_oom |
bool
|
If True, will handle out of memory errors elegantly |
True
|
**kwargs |
Additional keyword arguments to be passed to the |
{}
|
Returns:
Name | Type | Description |
---|---|---|
DataFrame |
The dataframe with the cross validation results |
Source code in src/pytorch_tabular/tabular_model.py
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 |
|
evaluate(test=None, test_loader=None, ckpt_path=None, verbose=True)
¶
Evaluates the dataframe using the loss and metrics already set in config.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
test |
Optional[DataFrame]
|
The dataframe to be evaluated. If not provided, will try to use the test provided during fit. If that was also not provided will return an empty dictionary |
None
|
test_loader |
Optional[DataLoader]
|
The dataloader to be used for evaluation. If provided, will use the dataloader instead of the test dataframe or the test data provided during fit. Defaults to None. |
None
|
ckpt_path |
Optional[Union[str, Path]]
|
The path to the checkpoint to be loaded. If not provided, will try to use the best checkpoint during training. |
None
|
verbose |
bool
|
If true, will print the results. Defaults to True. |
True
|
Returns: The final test result dictionary.
Source code in src/pytorch_tabular/tabular_model.py
explain(data, method='GradientShap', method_args={}, baselines=None, **kwargs)
¶
Returns the feature attributions/explanations of the model as a pandas DataFrame. The shape of the returned dataframe is (num_samples, num_features)
Parameters:
Name | Type | Description | Default |
---|---|---|---|
data |
DataFrame
|
The dataframe to be explained |
required |
method |
str
|
The method to be used for explaining the model. It should be one of the Defaults to "GradientShap". For more details, refer to https://captum.ai/api/attribution.html |
'GradientShap'
|
method_args |
Optional[Dict]
|
The arguments to be passed to the initialization of the Captum method. |
{}
|
baselines |
Union[float, tensor, str]
|
The baselines to be used for the explanation.
If a scalar is provided, will use that value as the baseline for all the features.
If a tensor is provided, will use that tensor as the baseline for all the features.
If a string like |
None
|
**kwargs |
Additional keyword arguments to be passed to the Captum method |
{}
|
Returns:
Name | Type | Description |
---|---|---|
DataFrame |
DataFrame
|
The dataframe with the feature importance |
Source code in src/pytorch_tabular/tabular_model.py
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 |
|
feature_importance()
¶
find_learning_rate(model, datamodule, min_lr=1e-08, max_lr=1, num_training=100, mode='exponential', early_stop_threshold=4.0, plot=True, callbacks=None)
¶
Enables the user to do a range test of good initial learning rates, to reduce the amount of guesswork in picking a good starting learning rate.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
model |
LightningModule
|
The PyTorch Lightning model to be trained. |
required |
datamodule |
TabularDatamodule
|
The datamodule |
required |
min_lr |
Optional[float]
|
minimum learning rate to investigate |
1e-08
|
max_lr |
Optional[float]
|
maximum learning rate to investigate |
1
|
num_training |
Optional[int]
|
number of learning rates to test |
100
|
mode |
Optional[str]
|
search strategy, either 'linear' or 'exponential'. If set to 'linear' the learning rate will be searched by linearly increasing after each batch. If set to 'exponential', will increase learning rate exponentially. |
'exponential'
|
early_stop_threshold |
Optional[float]
|
threshold for stopping the search. If the loss at any point is larger than early_stop_threshold*best_loss then the search is stopped. To disable, set to None. |
4.0
|
plot |
bool
|
If true, will plot using matplotlib |
True
|
callbacks |
Optional[List]
|
If provided, will be added to the callbacks for Trainer. |
None
|
Returns:
Type | Description |
---|---|
Tuple[float, DataFrame]
|
The suggested learning rate and the learning rate finder results |
Source code in src/pytorch_tabular/tabular_model.py
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 |
|
finetune(max_epochs=None, min_epochs=None, callbacks=None, freeze_backbone=False)
¶
Finetunes the model on the provided data.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
max_epochs |
Optional[int]
|
The maximum number of epochs to train for. Defaults to None. |
None
|
min_epochs |
Optional[int]
|
The minimum number of epochs to train for. Defaults to None. |
None
|
callbacks |
Optional[List[Callback]]
|
If provided, will be added to the callbacks for Trainer. Defaults to None. |
None
|
freeze_backbone |
bool
|
If True, will freeze the backbone by tirning off gradients. Defaults to False, which means the pretrained weights are also further tuned during fine-tuning. |
False
|
Returns:
Type | Description |
---|---|
Trainer
|
pl.Trainer: The trainer object |
Source code in src/pytorch_tabular/tabular_model.py
fit(train, validation=None, loss=None, metrics=None, metrics_prob_inputs=None, optimizer=None, optimizer_params=None, train_sampler=None, target_transform=None, max_epochs=None, min_epochs=None, seed=42, callbacks=None, datamodule=None, cache_data='memory', handle_oom=True)
¶
The fit method which takes in the data and triggers the training.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
train |
DataFrame
|
Training Dataframe |
required |
validation |
Optional[DataFrame]
|
If provided, will use this dataframe as the validation while training. Used in Early Stopping and Logging. If left empty, will use 20% of Train data as validation. Defaults to None. |
None
|
loss |
Optional[Module]
|
Custom Loss functions which are not in standard pytorch library |
None
|
metrics |
Optional[List[Callable]]
|
Custom metric functions(Callable) which has the signature metric_fn(y_hat, y) and works on torch tensor inputs. y_hat is expected to be of shape (batch_size, num_classes) for classification and (batch_size, 1) for regression and y is expected to be of shape (batch_size, 1) |
None
|
metrics_prob_inputs |
Optional[List[bool]]
|
This is a mandatory parameter for classification metrics. If the metric function requires probabilities as inputs, set this to True. The length of the list should be equal to the number of metrics. Defaults to None. |
None
|
optimizer |
Optional[Optimizer]
|
Custom optimizers which are a drop in replacements for standard PyTorch optimizers. This should be the Class and not the initialized object |
None
|
optimizer_params |
Optional[Dict]
|
The parameters to initialize the custom optimizer. |
None
|
train_sampler |
Optional[Sampler]
|
Custom PyTorch batch samplers which will be passed to the DataLoaders. Useful for dealing with imbalanced data and other custom batching strategies |
None
|
target_transform |
Optional[Union[TransformerMixin, Tuple(Callable)]]
|
If provided, applies the transform to the target before modelling and inverse the transform during prediction. The parameter can either be a sklearn Transformer which has an inverse_transform method, or a tuple of callables (transform_func, inverse_transform_func) |
None
|
max_epochs |
Optional[int]
|
Overwrite maximum number of epochs to be run. Defaults to None. |
None
|
min_epochs |
Optional[int]
|
Overwrite minimum number of epochs to be run. Defaults to None. |
None
|
seed |
Optional[int]
|
(int): Random seed for reproducibility. Defaults to 42. |
42
|
callbacks |
Optional[List[Callback]]
|
List of callbacks to be used during training. Defaults to None. |
None
|
datamodule |
Optional[TabularDatamodule]
|
The datamodule. If provided, will ignore the rest of the parameters like train, test etc and use the datamodule. Defaults to None. |
None
|
cache_data |
str
|
Decides how to cache the data in the dataloader. If set to "memory", will cache in memory. If set to a valid path, will cache in that path. Defaults to "memory". |
'memory'
|
handle_oom |
bool
|
If True, will try to handle OOM errors elegantly. Defaults to True. |
True
|
Returns:
Type | Description |
---|---|
Trainer
|
pl.Trainer: The PyTorch Lightning Trainer instance |
Source code in src/pytorch_tabular/tabular_model.py
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 |
|
load_best_model()
¶
Loads the best model after training is done.
Source code in src/pytorch_tabular/tabular_model.py
load_model(dir, map_location=None, strict=True)
classmethod
¶
Loads a saved model from the directory.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
dir |
str
|
The directory where the model wa saved, along with the checkpoints |
required |
map_location |
Union[Dict[str, str], str, device, int, Callable, None])
|
If your checkpoint saved a GPU model and you now load on CPUs or a different number of GPUs, use this to map to the new setup. The behaviour is the same as in torch.load() |
None
|
strict |
bool)
|
Whether to strictly enforce that the keys in checkpoint_path match the keys returned by this module's state dict. Default: True. |
True
|
Returns:
Name | Type | Description |
---|---|---|
TabularModel |
TabularModel
|
The saved TabularModel |
Source code in src/pytorch_tabular/tabular_model.py
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 |
|
load_weights(path)
¶
Loads the model weights in the specified directory.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
path |
str
|
The path to the file to load the model from |
required |
Source code in src/pytorch_tabular/tabular_model.py
predict(test, quantiles=[0.25, 0.5, 0.75], n_samples=100, ret_logits=False, include_input_features=False, device=None, progress_bar=None, test_time_augmentation=False, num_tta=5, alpha_tta=0.1, aggregate_tta='mean', tta_seed=42)
¶
Uses the trained model to predict on new data and return as a dataframe.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
test |
DataFrame
|
The new dataframe with the features defined during training |
required |
quantiles |
Optional[List]
|
For probabilistic models like Mixture Density Networks, this specifies
the different quantiles to be extracted apart from the |
[0.25, 0.5, 0.75]
|
n_samples |
Optional[int]
|
Number of samples to draw from the posterior to estimate the quantiles. Ignored for non-probabilistic models. Defaults to 100 |
100
|
ret_logits |
bool
|
Flag to return raw model outputs/logits except the backbone features along with the dataframe. Defaults to False |
False
|
include_input_features |
bool
|
DEPRECATED: Flag to include the input features in the returned dataframe. Defaults to True |
False
|
progress_bar |
Optional[str]
|
choose progress bar for tracking the progress. "rich" or "tqdm" will set the respective progress bars. If None, no progress bar will be shown. |
None
|
test_time_augmentation |
bool
|
If True, will use test time augmentation to generate predictions. The approach is very similar to what is described here But, we add noise to the embedded inputs to handle categorical features as well. (x_{aug} = x_{orig} + lpha * \epsilon) where (\epsilon \sim \mathcal{N}(0, 1)) Defaults to False |
False
|
num_tta |
float
|
The number of augumentations to run TTA for. Defaults to 0.0 |
5
|
alpha_tta |
float
|
The standard deviation of the gaussian noise to be added to the input features |
0.1
|
aggregate_tta |
Union[str, Callable]
|
The function to be used to aggregate the predictions from each augumentation. If str, should be one of "mean", "median", "min", or "max" for regression. For classification, the previous options are applied to the confidence scores (soft voting) and then converted to final prediction. An additional option "hard_voting" is available for classification. If callable, should be a function that takes in a list of 3D arrays (num_samples, num_cv, num_targets) and returns a 2D array of final probabilities (num_samples, num_targets). Defaults to "mean".' |
'mean'
|
tta_seed |
int
|
The random seed to be used for the noise added in TTA. Defaults to 42. |
42
|
Returns:
Name | Type | Description |
---|---|---|
DataFrame |
DataFrame
|
Returns a dataframe with predictions and features (if |
Source code in src/pytorch_tabular/tabular_model.py
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 |
|
prepare_dataloader(train, validation=None, train_sampler=None, target_transform=None, seed=42, cache_data='memory')
¶
Prepares the dataloaders for training and validation.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
train |
DataFrame
|
Training Dataframe |
required |
validation |
Optional[DataFrame]
|
If provided, will use this dataframe as the validation while training. Used in Early Stopping and Logging. If left empty, will use 20% of Train data as validation. Defaults to None. |
None
|
train_sampler |
Optional[Sampler]
|
Custom PyTorch batch samplers which will be passed to the DataLoaders. Useful for dealing with imbalanced data and other custom batching strategies |
None
|
target_transform |
Optional[Union[TransformerMixin, Tuple(Callable)]]
|
If provided, applies the transform to the target before modelling and inverse the transform during prediction. The parameter can either be a sklearn Transformer which has an inverse_transform method, or a tuple of callables (transform_func, inverse_transform_func) |
None
|
seed |
Optional[int]
|
Random seed for reproducibility. Defaults to 42. |
42
|
cache_data |
str
|
Decides how to cache the data in the dataloader. If set to "memory", will cache in memory. If set to a valid path, will cache in that path. Defaults to "memory". |
'memory'
|
Returns: TabularDatamodule: The prepared datamodule
Source code in src/pytorch_tabular/tabular_model.py
prepare_model(datamodule, loss=None, metrics=None, metrics_prob_inputs=None, optimizer=None, optimizer_params=None)
¶
Prepares the model for training.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
datamodule |
TabularDatamodule
|
The datamodule |
required |
loss |
Optional[Module]
|
Custom Loss functions which are not in standard pytorch library |
None
|
metrics |
Optional[List[Callable]]
|
Custom metric functions(Callable) which has the signature metric_fn(y_hat, y) and works on torch tensor inputs |
None
|
metrics_prob_inputs |
Optional[List[bool]]
|
This is a mandatory parameter for classification metrics. If the metric function requires probabilities as inputs, set this to True. The length of the list should be equal to the number of metrics. Defaults to None. |
None
|
optimizer |
Optional[Optimizer]
|
Custom optimizers which are a drop in replacements for standard PyTorch optimizers. This should be the Class and not the initialized object |
None
|
optimizer_params |
Optional[Dict]
|
The parameters to initialize the custom optimizer. |
None
|
Returns:
Name | Type | Description |
---|---|---|
BaseModel |
BaseModel
|
The prepared model |
Source code in src/pytorch_tabular/tabular_model.py
pretrain(train, validation=None, optimizer=None, optimizer_params=None, max_epochs=None, min_epochs=None, seed=42, callbacks=None, datamodule=None, cache_data='memory')
¶
The pretrained method which takes in the data and triggers the training.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
train |
DataFrame
|
Training Dataframe |
required |
validation |
Optional[DataFrame]
|
If provided, will use this dataframe as the validation while training. Used in Early Stopping and Logging. If left empty, will use 20% of Train data as validation. Defaults to None. |
None
|
optimizer |
Optional[Optimizer]
|
Custom optimizers which are a drop in replacements for standard PyTorch optimizers. This should be the Class and not the initialized object |
None
|
optimizer_params |
Optional[Dict]
|
The parameters to initialize the custom optimizer. |
None
|
max_epochs |
Optional[int]
|
Overwrite maximum number of epochs to be run. Defaults to None. |
None
|
min_epochs |
Optional[int]
|
Overwrite minimum number of epochs to be run. Defaults to None. |
None
|
seed |
Optional[int]
|
(int): Random seed for reproducibility. Defaults to 42. |
42
|
callbacks |
Optional[List[Callback]]
|
List of callbacks to be used during training. Defaults to None. |
None
|
datamodule |
Optional[TabularDatamodule]
|
The datamodule. If provided, will ignore the rest of the parameters like train, test etc. and use the datamodule. Defaults to None. |
None
|
cache_data |
str
|
Decides how to cache the data in the dataloader. If set to "memory", will cache in memory. If set to a valid path, will cache in that path. Defaults to "memory". |
'memory'
|
Returns: pl.Trainer: The PyTorch Lightning Trainer instance
Source code in src/pytorch_tabular/tabular_model.py
save_config(dir)
¶
Saves the config in the specified directory.
save_datamodule(dir, inference_only=False)
¶
Saves the datamodule in the specified directory.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
dir |
str
|
The path to the directory to save the datamodule |
required |
inference_only |
bool
|
If True, will only save the inference datamodule without data. This cannot be used for further training, but can be used for inference. Defaults to False. |
False
|
Source code in src/pytorch_tabular/tabular_model.py
save_model(dir, inference_only=False)
¶
Saves the model and checkpoints in the specified directory.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
dir |
str
|
The path to the directory to save the model |
required |
inference_only |
bool
|
If True, will only save the inference only version of the datamodule |
False
|
Source code in src/pytorch_tabular/tabular_model.py
save_model_for_inference(path, kind='pytorch', onnx_export_params={'opset_version': 12})
¶
Saves the model for inference.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
path |
Union[str, Path]
|
path to save the model |
required |
kind |
str
|
"pytorch" or "onnx" (Experimental) |
'pytorch'
|
onnx_export_params |
Dict
|
parameters for onnx export to be passed to torch.onnx.export |
{'opset_version': 12}
|
Returns:
Name | Type | Description |
---|---|---|
bool |
bool
|
True if the model was saved successfully |
Source code in src/pytorch_tabular/tabular_model.py
save_weights(path)
¶
Saves the model weights in the specified directory.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
path |
str
|
The path to the file to save the model |
required |
Source code in src/pytorch_tabular/tabular_model.py
summary(model=None, max_depth=-1)
¶
Prints a summary of the model.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
max_depth |
int
|
The maximum depth to traverse the modules and displayed in the summary. Defaults to -1, which means will display all the modules. |
-1
|
Source code in src/pytorch_tabular/tabular_model.py
train(model, datamodule, callbacks=None, max_epochs=None, min_epochs=None, handle_oom=True)
¶
Trains the model.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
model |
LightningModule
|
The PyTorch Lightning model to be trained. |
required |
datamodule |
TabularDatamodule
|
The datamodule |
required |
callbacks |
Optional[List[Callback]]
|
List of callbacks to be used during training. Defaults to None. |
None
|
max_epochs |
Optional[int]
|
Overwrite maximum number of epochs to be run. Defaults to None. |
None
|
min_epochs |
Optional[int]
|
Overwrite minimum number of epochs to be run. Defaults to None. |
None
|
handle_oom |
bool
|
If True, will try to handle OOM errors elegantly. Defaults to True. |
True
|
Returns:
Type | Description |
---|---|
Trainer
|
pl.Trainer: The PyTorch Lightning Trainer instance |
Source code in src/pytorch_tabular/tabular_model.py
Bases: LightningDataModule
Source code in src/pytorch_tabular/tabular_datamodule.py
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 |
|
categorical_encoder
property
writable
¶
Returns the categorical encoder.
continuous_transform
property
writable
¶
Returns the continuous transform.
label_encoder
property
writable
¶
Returns the label encoder.
scaler
property
writable
¶
Returns the scaler.
target_transforms
property
writable
¶
Returns the target transforms.
train_dataset: TabularDataset
property
writable
¶
Returns the train dataset.
Returns:
Name | Type | Description |
---|---|---|
TabularDataset |
TabularDataset
|
The train dataset |
validation_dataset: TabularDataset
property
writable
¶
Returns the validation dataset.
Returns:
Name | Type | Description |
---|---|---|
TabularDataset |
TabularDataset
|
The validation dataset |
__init__(train, config, validation=None, target_transform=None, train_sampler=None, seed=42, cache_data='memory', copy_data=True, verbose=True)
¶
The Pytorch Lightning Datamodule for Tabular Data.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
train |
DataFrame
|
The Training Dataframe |
required |
config |
DictConfig
|
Merged configuration object from ModelConfig, DataConfig, TrainerConfig, OptimizerConfig & ExperimentConfig |
required |
validation |
DataFrame
|
Validation Dataframe. If left empty, we use the validation split from DataConfig to split a random sample as validation. Defaults to None. |
None
|
target_transform |
Optional[Union[TransformerMixin, Tuple(Callable)]]
|
If provided, applies the transform to the target before modelling and inverse the transform during prediction. The parameter can either be a sklearn Transformer which has an inverse_transform method, or a tuple of callables (transform_func, inverse_transform_func) Defaults to None. |
None
|
train_sampler |
Optional[Sampler]
|
If provided, the sampler will be used to sample the train data. Defaults to None. |
None
|
seed |
Optional[int]
|
Seed to use for reproducible dataloaders. Defaults to 42. |
42
|
cache_data |
str
|
Decides how to cache the data in the dataloader. If set to "memory", will cache in memory. If set to a valid path, will cache in that path. Defaults to "memory". |
'memory'
|
copy_data |
bool
|
If True, will copy the dataframes before preprocessing. Defaults to True. |
True
|
verbose |
bool
|
Sets the verbosity of the databodule logging |
True
|
Source code in src/pytorch_tabular/tabular_datamodule.py
add_datepart(df, field_name, frequency, prefix=None, drop=True)
classmethod
¶
Helper function that adds columns relevant to a date in the column field_name
of df
.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
df |
DataFrame
|
Dataframe |
required |
field_name |
str
|
Date field name |
required |
frequency |
str
|
Frequency string of the form |
required |
prefix |
str
|
Prefix to add to the new columns. Defaults to None. |
None
|
drop |
bool
|
Drop the original column. Defaults to True. |
True
|
Returns:
Type | Description |
---|---|
Tuple[DataFrame, List[str]]
|
Dataframe with added columns and list of added columns |
Source code in src/pytorch_tabular/tabular_datamodule.py
inference_only_copy()
¶
Creates a copy of the datamodule with the train and validation datasets removed. This is useful for inference only scenarios where we don't want to save the train and validation datasets.
Returns:
Name | Type | Description |
---|---|---|
TabularDatamodule |
A copy of the datamodule with the train and validation datasets removed. |
Source code in src/pytorch_tabular/tabular_datamodule.py
load_datamodule(path)
classmethod
¶
Loads a datamodule from a path.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
path |
Union[str, Path]
|
Path to the datamodule |
required |
Returns:
Name | Type | Description |
---|---|---|
TabularDatamodule |
TabularDatamodule
|
The datamodule loaded from the path |
Source code in src/pytorch_tabular/tabular_datamodule.py
make_date(df, date_field, date_format='ISO8601')
classmethod
¶
Make sure df[date_field]
is of the right date type.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
df |
DataFrame
|
Dataframe |
required |
date_field |
str
|
Date field name |
required |
Returns:
Type | Description |
---|---|
DataFrame
|
Dataframe with date field converted to datetime |
Source code in src/pytorch_tabular/tabular_datamodule.py
prepare_inference_dataloader(df, batch_size=None, copy_df=True)
¶
Function that prepares and loads the new data.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
df |
DataFrame
|
Dataframe with the features and target |
required |
batch_size |
Optional[int]
|
Batch size. Defaults to |
None
|
copy_df |
bool
|
Whether to copy the dataframe before processing or not. Defaults to False. |
True
|
Returns: DataLoader: The dataloader for the passed in dataframe
Source code in src/pytorch_tabular/tabular_datamodule.py
preprocess_data(data, stage='inference')
¶
The preprocessing, like Categorical Encoding, Normalization, etc. which any dataframe should undergo before feeding into the dataloder.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
data |
DataFrame
|
A dataframe with the features and target |
required |
stage |
str
|
Internal parameter. Used to distinguisj between fit and inference. Defaults to "inference". |
'inference'
|
Returns:
Type | Description |
---|---|
Tuple[DataFrame, list]
|
Returns the processed dataframe and the added features(list) as a tuple |
Source code in src/pytorch_tabular/tabular_datamodule.py
save_dataloader(path)
¶
Saves the dataloader to a path.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
path |
Union[str, Path]
|
Path to save the dataloader |
required |
Source code in src/pytorch_tabular/tabular_datamodule.py
setup(stage=None)
¶
Data Operations you want to perform on all GPUs, like train-test split, transformations, etc. This is called before accessing the dataloaders.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
stage |
Optional[str]
|
Internal parameter to distinguish between fit and inference. Defaults to None. |
None
|
Source code in src/pytorch_tabular/tabular_datamodule.py
time_features_from_frequency_str(freq_str)
classmethod
¶
Returns a list of time features that will be appropriate for the given frequency string.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
freq_str |
str
|
Frequency string of the form |
required |
Returns:
Type | Description |
---|---|
List[str]
|
List of added features |
Source code in src/pytorch_tabular/tabular_datamodule.py
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 |
|
train_dataloader(batch_size=None)
¶
Function that loads the train set.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
batch_size |
Optional[int]
|
Batch size. Defaults to |
None
|
Returns:
Name | Type | Description |
---|---|---|
DataLoader |
DataLoader
|
Train dataloader |
Source code in src/pytorch_tabular/tabular_datamodule.py
update_config(config)
¶
Calculates and updates a few key information to the config object. Logic happens in _update_config. This is just a wrapper to make it accessible from outside and not break current apis.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
config |
DictConfig
|
The config object |
required |
Returns:
Name | Type | Description |
---|---|---|
InferredConfig |
InferredConfig
|
The updated config object |
Source code in src/pytorch_tabular/tabular_datamodule.py
val_dataloader(batch_size=None)
¶
Function that loads the validation set.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
batch_size |
Optional[int]
|
Batch size. Defaults to |
None
|
Returns:
Name | Type | Description |
---|---|---|
DataLoader |
DataLoader
|
Validation dataloader |
Source code in src/pytorch_tabular/tabular_datamodule.py
Tabular Model Tuner.
This class is used to tune the hyperparameters of a TabularModel, given the search space, strategy and metric to optimize.
Source code in src/pytorch_tabular/tabular_model_tuner.py
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 |
|
__init__(data_config=None, model_config=None, optimizer_config=None, trainer_config=None, model_callable=None, model_state_dict_path=None, suppress_lightning_logger=True, **kwargs)
¶
Tabular Model Tuner helps you tune the hyperparameters of a TabularModel.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
data_config |
Optional[Union[DataConfig, str]]
|
The DataConfig for the TabularModel. If str is passed, will initialize the DataConfig using the yaml file in that path. Defaults to None. |
None
|
model_config |
Optional[Union[ModelConfig, str]]
|
The ModelConfig for the TabularModel. If str is passed, will initialize the ModelConfig using the yaml file in that path. Defaults to None. |
None
|
optimizer_config |
Optional[Union[OptimizerConfig, str]]
|
The OptimizerConfig for the TabularModel. If str is passed, will initialize the OptimizerConfig using the yaml file in that path. Defaults to None. |
None
|
trainer_config |
Optional[Union[TrainerConfig, str]]
|
The TrainerConfig for the TabularModel. If str is passed, will initialize the TrainerConfig using the yaml file in that path. Defaults to None. |
None
|
model_callable |
Optional[Callable]
|
A callable that returns a PyTorch Tabular Model. If provided, will ignore the model_config and use this callable to initialize the model. Defaults to None. |
None
|
model_state_dict_path |
Optional[Union[str, Path]]
|
Path to the state dict of the model. If provided, will ignore the model_config and use this state dict to initialize the model. Defaults to None. |
None
|
suppress_lightning_logger |
bool
|
Whether to suppress the lightning logger. Defaults to True. |
True
|
**kwargs |
Additional keyword arguments to be passed to the TabularModel init. |
{}
|
Source code in src/pytorch_tabular/tabular_model_tuner.py
tune(train, search_space, metric, mode, strategy, validation=None, n_trials=None, cv=None, cv_agg_func=np.mean, cv_kwargs={}, return_best_model=True, verbose=False, progress_bar=True, random_state=42, ignore_oom=True, **kwargs)
¶
Tune the hyperparameters of the TabularModel.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
train |
DataFrame
|
Training data |
required |
validation |
DataFrame
|
Validation data. Defaults to None. |
None
|
search_space |
Dict
|
A dictionary of the form {param_name: [values to try]} for grid search or {param_name: distribution} for random search |
required |
metric |
Union[str, Callable]
|
The metric to be used for evaluation.
If str is provided, will use that metric from the defined ones.
If callable is provided, will use that function as the metric.
We expect callable to be of the form |
required |
mode |
str
|
One of ['max', 'min']. Whether to maximize or minimize the metric. |
required |
strategy |
str
|
One of ['grid_search', 'random_search']. The strategy to use for tuning. |
required |
n_trials |
int
|
Number of trials to run. Only used for random search. Defaults to None. |
None
|
cv |
Optional[Union[int, Iterable, BaseCrossValidator]]
|
Determines the cross-validation splitting strategy. Possible inputs for cv are:
|
None
|
cv_agg_func |
Optional[Callable]
|
Function to aggregate the cross validation scores. Defaults to np.mean. |
mean
|
cv_kwargs |
Optional[Dict]
|
Additional keyword arguments to be passed to the cross validation method. Defaults to {}. |
{}
|
return_best_model |
bool
|
If True, will return the best model. Defaults to True. |
True
|
verbose |
bool
|
Whether to print the results of each trial. Defaults to False. |
False
|
progress_bar |
bool
|
Whether to show a progress bar. Defaults to True. |
True
|
random_state |
Optional[int]
|
Random state to be used for random search. Defaults to 42. |
42
|
ignore_oom |
bool
|
Whether to ignore out of memory errors. Defaults to True. |
True
|
**kwargs |
Additional keyword arguments to be passed to the TabularModel fit. |
{}
|
Returns:
Name | Type | Description |
---|---|---|
OUTPUT |
A named tuple with the following attributes: trials_df (DataFrame): A dataframe with the results of each trial best_params (Dict): The best parameters found best_score (float): The best score found best_model (TabularModel or None): If return_best_model is True, return best_model otherwise return None |
Source code in src/pytorch_tabular/tabular_model_tuner.py
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 |
|
Compare multiple models on the same dataset.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
task |
str
|
The type of prediction task. Either 'classification' or 'regression' |
required |
train |
DataFrame
|
The training data |
required |
test |
DataFrame
|
The test data on which performance is evaluated |
required |
data_config |
Union[DataConfig, str]
|
DataConfig object or path to the yaml file. |
required |
optimizer_config |
Union[OptimizerConfig, str]
|
OptimizerConfig object or path to the yaml file. |
required |
trainer_config |
Union[TrainerConfig, str]
|
TrainerConfig object or path to the yaml file. |
required |
model_list |
Union[str, List[Union[ModelConfig, str]]]
|
The list of models to compare.
This can be one of the presets defined in |
'lite'
|
metrics |
Optional[List[str]]
|
the list of metrics you need to track during training. The metrics
should be one of the functional metrics implemented in |
None
|
metrics_prob_input |
Optional[bool]
|
Is a mandatory parameter for classification metrics defined in the config. This defines whether the input to the metric function is the probability or the class. Length should be same as the number of metrics. Defaults to None. |
None
|
metrics_params |
Optional[List]
|
The parameters to be passed to the metrics function. |
None
|
validation |
Optional[DataFrame]
|
|
None
|
experiment_config |
Optional[Union[ExperimentConfig, str]]
|
ExperimentConfig object or path to the yaml file. |
None
|
common_model_args |
Optional[dict]
|
The model argument which are common to all models. The list
of params can be found in |
{}
|
rank_metric |
Optional[Tuple[str, str]]
|
The metric to use for ranking the models. The first element of the tuple is the metric name and the second element is the direction. Defaults to ('loss', "lower_is_better"). |
('loss', 'lower_is_better')
|
return_best_model |
bool
|
If True, will return the best model. Defaults to True. |
True
|
seed |
int
|
The seed for reproducibility. Defaults to 42. |
42
|
ignore_oom |
bool
|
If True, will ignore the Out of Memory error and continue with the next model. |
True
|
progress_bar |
bool
|
If True, will show a progress bar. Defaults to True. |
True
|
verbose |
bool
|
If True, will print the progress. Defaults to True. |
True
|
suppress_lightning_logger |
bool
|
If True, will suppress the lightning logger. Defaults to True. |
True
|
Returns |
results: Training results. best_model: If return_best_model is True, return best_model otherwise return None. |
required |
Source code in src/pytorch_tabular/tabular_model_sweep.py
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 |
|