Modeling_Tool.Model¶
Model training layer: logistic regression (LRMaster), gradient boosting with LightGBM, XGBoost, and CatBoost
(GradientBoostingModel), and backward variable elimination. The subpackage loads on first access of one of its names, and
the boosting libraries load when you build a model of that type.
Logistic Regression: LRM_Tool¶
LRM_Tool
¶
FeatureSelectionAnalyzer
¶
Feature selection analyzer using statistical tests.
Analyzes feature relevance using chi-squared tests, correlation analysis, and variance inflation factor (VIF) for multicollinearity detection.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
significance_level
|
float
|
Significance level for statistical tests |
0.05
|
Attributes:
| Name | Type | Description |
|---|---|---|
significance_level |
float
|
Significance level; |
selected_features_ |
list of str or None
|
Features selected by the last |
chi2_results_ |
DataFrame or None
|
Result table of the last |
Examples:
>>> analyzer = FeatureSelectionAnalyzer(significance_level=0.05)
>>> results = analyzer.chi2_selection(train_df, feature_cols, 'target')
>>> vif_df = analyzer.compute_vif(train_df[feature_cols])
Source code in Modeling_Tool/Model/LRM_Tool.py
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 | |
chi2_selection
¶
chi2_selection(data, feature_cols, target_col, nan_handling='fillna_median', nan_warn_threshold=0.05)
Select features using chi-squared test.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame
|
Input data |
required |
feature_cols
|
list of str
|
Feature column names to evaluate |
required |
target_col
|
str
|
Target variable column name |
required |
nan_handling
|
str
|
How missing values in the feature columns are handled before the test. |
"fillna_median"
|
nan_warn_threshold
|
float
|
A |
0.05
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
Results with columns ['feature', 'chi2', 'p_value', 'selected'], sorted by |
Notes
The features are scaled to [0, 1] with MinMaxScaler before the test, because the chi-squared statistic needs
non-negative values. The result table is also stored in chi2_results_ and the selected feature names in
selected_features_.
Source code in Modeling_Tool/Model/LRM_Tool.py
compute_vif
¶
Compute Variance Inflation Factor (VIF) for multicollinearity detection.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame
|
Feature matrix (should not include target variable) |
required |
nan_handling
|
str
|
How missing values are handled before the VIF is computed. Same options as in |
"fillna_median"
|
nan_warn_threshold
|
float
|
A |
0.05
|
sample_weight
|
array - like
|
Per-row frequency/sample weights, one per row of |
None
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
DataFrame with columns ['feature', 'VIF'] sorted by VIF descending. Perfectly collinear features get a very large or infinite VIF. |
Raises:
| Type | Description |
|---|---|
ImportError
|
If |
Source code in Modeling_Tool/Model/LRM_Tool.py
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 | |
correlation_filter
¶
Remove highly correlated features.
The absolute pairwise Pearson correlations of the columns are compared with threshold: when two columns
correlate above it, the one that comes later in data is dropped. data itself is not modified; the
names of the kept columns are returned.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame
|
Feature matrix |
required |
threshold
|
float
|
Correlation threshold above which features are removed (an absolute correlation strictly greater than the threshold) |
0.8
|
Returns:
| Type | Description |
|---|---|
list of str
|
List of features to keep (low correlation subset), in the column order of |
Source code in Modeling_Tool/Model/LRM_Tool.py
LRMaster
¶
Logistic Regression Master Class.
A unified wrapper for logistic regression modeling that encapsulates:
- Model training and prediction
- Variable importance analysis
- Statistical summary generation
- Stepwise variable selection
- Holdout-based hyperparameter grid search
- AIC/BIC calculation
- Optional feature standardization (off by default)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
params
|
dict
|
Parameters for sklearn LogisticRegression, e.g., {'C': 1.0, 'solver': 'lbfgs'} |
None
|
model
|
sklearn-like LogisticRegression object
|
Existing fitted LR model object. If provided, LRMaster will wrap this model directly. |
None
|
varlist
|
list
|
Feature names used by the existing model. Required when model does not have
|
None
|
tgt_name
|
str
|
Target variable name. Useful when wrapping an existing fitted model and later calling summary/evaluation methods. |
None
|
standardize
|
bool
|
If True, fit a scaler on the training features during |
False
|
scaler
|
sklearn-like transformer
|
Custom scaler prototype to use when |
None
|
Attributes:
| Name | Type | Description |
|---|---|---|
params |
dict
|
Model parameters (a sanitized copy of the |
model |
LogisticRegression
|
Trained model (None until fit() is called) |
calibrated_model |
CalibratedClassifierCV or None
|
Calibrated model stored by calibrate_model() (None until it runs; fit() does not reset it) |
varlist |
list
|
List of feature names |
tgt_name |
str
|
Target variable name |
standardize |
bool
|
Whether feature standardization is enabled |
standardizer |
sklearn-like scaler or None
|
Fitted scaler (None until fit() runs with standardize=True) |
best_params_ |
dict or None
|
Best hyperparameters from grid_search_params (None until it runs) |
search_results_ |
DataFrame or None
|
Full grid_search_params results table (None until it runs) |
Examples:
>>> lr = LRMaster(params={'C': 1.0, 'solver': 'lbfgs'})
>>> lr.fit(train_df, ['age', 'income'], 'target')
>>> predictions = lr.predict(test_df)
>>> importance = lr.get_variable_importance()
>>> # With standardization (defaults to StandardScaler)
>>> lr = LRMaster(params={'C': 1.0}, standardize=True)
>>> lr.fit(train_df, ['age', 'income'], 'target')
>>> proba = lr.predict_proba(test_df) # test_df is scaled with the fitted scaler
Source code in Modeling_Tool/Model/LRM_Tool.py
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 | |
set_data
¶
Store reference data for later use (e.g., calibration).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame
|
Training data to store |
required |
Returns:
| Type | Description |
|---|---|
self
|
|
Source code in Modeling_Tool/Model/LRM_Tool.py
fit
¶
Train the logistic regression model.
When standardize=True, a scaler is fitted on the training features and
stored as self.standardizer; the model is then trained on the scaled
features. The same scaler is reused at prediction / evaluation time.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame
|
Training dataset containing features and target |
required |
varlist
|
list of str
|
Feature column names to use for training |
required |
tgt_name
|
str
|
Target variable column name |
required |
val_data
|
DataFrame
|
Validation dataset (currently used for reference; not used in fitting) |
None
|
val_varlist
|
list of str
|
Validation feature column names |
None
|
val_tgt_name
|
str
|
Validation target variable column name |
None
|
weight_col
|
str
|
Column in |
None
|
Returns:
| Type | Description |
|---|---|
self
|
The fitted |
Notes
Besides fitting model, this call sets varlist and tgt_name and keeps a reference to data, which
get_statsmodel_summary, get_aic, get_bic and calibrate_model use when they are called without
data (the reference is not pickled). calibrated_model is not reset: call calibrate_model again after
refitting.
Source code in Modeling_Tool/Model/LRM_Tool.py
calibrate_model
¶
calibrate_model(model=None, train_df=None, method='sigmoid', cv=5, weight_col=None, sample_weight=None)
Model calibration with optional sample weights.
Wrap the model in a scikit-learn CalibratedClassifierCV and fit it; the result is stored as
self.calibrated_model and is used by predict and predict_proba when they are called with
calibrated_model=True.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
sklearn-like LogisticRegression object
|
Model to calibrate. Defaults to |
None
|
train_df
|
DataFrame
|
Calibration data, with the model's feature columns and the target column |
None
|
method
|
str
|
Calibration method, |
'sigmoid'
|
cv
|
int or str
|
Cross-validation strategy of |
5
|
weight_col
|
str
|
Name of a column of |
None
|
sample_weight
|
array - like
|
Per-row sample weights aligned with |
None
|
Returns:
| Type | Description |
|---|---|
self
|
The |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the feature list cannot be inferred (the model has no |
KeyError
|
If |
Notes
The calibration features are scaled with the fitted standardizer when standardize=True, so the calibrated
model works in the same feature space as model.
Source code in Modeling_Tool/Model/LRM_Tool.py
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 | |
eval_calibrated_outcome
¶
Evaluate calibrated vs raw probabilities on a holdout set.
Compute the Brier score of the raw and of the calibrated positive-class probabilities of evalset and,
optionally, plot the reliability curves of both. calibrate_model must have been called first.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
evalset
|
DataFrame
|
Holdout data with the feature columns of |
required |
plot
|
bool
|
If True, show a matplotlib reliability plot (10 bins) with the raw curve, the calibrated curve and the diagonal of perfect calibration. |
False
|
weight_col
|
str
|
Name of a column of |
None
|
sample_weight
|
array - like
|
Per-row weights aligned with |
None
|
Returns:
| Type | Description |
|---|---|
None
|
Nothing is returned. The two Brier scores are written with |
Notes
The calibration curves are weighted only when the installed scikit-learn accepts sample_weight in
calibration_curve; otherwise the curves are computed unweighted (the Brier scores stay weighted).
Source code in Modeling_Tool/Model/LRM_Tool.py
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 | |
predict
¶
Predict using the trained model.
When standardization is enabled, the input features are scaled with the
scaler fitted during fit before being passed to the model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame
|
Input data for prediction |
required |
varlist
|
list
|
Feature names (uses training features if None) |
None
|
calibrated_model
|
bool
|
If True, predict with the calibrated model stored by |
False
|
Returns:
| Type | Description |
|---|---|
ndarray
|
Predicted class labels (hard labels such as 0/1, not probabilities; use |
Source code in Modeling_Tool/Model/LRM_Tool.py
predict_proba
¶
Predict class probabilities.
When standardization is enabled, the input features are scaled with the
scaler fitted during fit before being passed to the model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame
|
Input data for prediction |
required |
varlist
|
list
|
Feature names (uses training features if None) |
None
|
calibrated_model
|
bool
|
If True, return the probabilities of the calibrated model stored by |
False
|
Returns:
| Type | Description |
|---|---|
ndarray
|
Array of shape (n_samples, 2) with class probabilities (the columns follow the model's |
Source code in Modeling_Tool/Model/LRM_Tool.py
get_variable_importance
¶
Get variable importance (coefficients) from the model.
Returns:
| Type | Description |
|---|---|
DataFrame
|
DataFrame with columns ['varlist', 'coef', 'importance'] sorted by importance in descending order |
Notes
When standardization is enabled the coefficients are expressed in the standardized feature space (i.e. they are directly comparable in magnitude across features).
Source code in Modeling_Tool/Model/LRM_Tool.py
get_statsmodel_summary
¶
Generate a statsmodels-style summary for the trained LR model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame
|
Data for computing the summary (uses stored training data if None) |
None
|
varlist
|
list of str
|
Feature names (uses stored varlist if None) |
None
|
tgt_name
|
str
|
Target variable name (uses stored tgt_name if None) |
None
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
Summary table with coefficients, standard errors, z-scores and p-values (columns |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Notes
When standardization is enabled the summary is computed on the standardized feature space, consistent with how the model was trained.
Source code in Modeling_Tool/Model/LRM_Tool.py
get_aic
¶
Compute AIC for the trained model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame
|
Data to evaluate the model on (uses the stored training data if None). |
None
|
varlist
|
list of str
|
Feature names (uses the stored varlist if None). |
None
|
tgt_name
|
str
|
Target variable name (uses the stored tgt_name if None). |
None
|
weight_col
|
str
|
Name of a column of |
None
|
Returns:
| Type | Description |
|---|---|
float
|
AIC value (lower is better). |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
KeyError
|
If |
Source code in Modeling_Tool/Model/LRM_Tool.py
get_bic
¶
Compute BIC for the trained model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame
|
Data to evaluate the model on (uses the stored training data if None). |
None
|
varlist
|
list of str
|
Feature names (uses the stored varlist if None). |
None
|
tgt_name
|
str
|
Target variable name (uses the stored tgt_name if None). |
None
|
weight_col
|
str
|
Name of a column of |
None
|
Returns:
| Type | Description |
|---|---|
float
|
BIC value (lower is better). |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
KeyError
|
If |
Source code in Modeling_Tool/Model/LRM_Tool.py
stepwise_selection
¶
stepwise_selection(data, varlist, tgt_name, criterion='aic', direction='both', max_iter=100, verbose=True, weight_col=None)
Perform stepwise variable selection.
Iteratively adds or removes features based on AIC/BIC improvement.
When standardize=True, all interim fits and the final model are
trained on standardized features, and the fitted scaler for the selected
columns is stored on the instance for later prediction.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame
|
Training data |
required |
varlist
|
list of str
|
Initial feature list (the candidate variables). With |
required |
tgt_name
|
str
|
Target variable name |
required |
criterion
|
str
|
Selection criterion, 'aic' or 'bic'. Any value other than 'aic' selects by BIC. |
'aic'
|
direction
|
str
|
Direction of stepwise selection: 'forward', 'backward', or 'both'. 'both' starts from all variables like
'backward' but can add a removed variable back. Any other value performs no step and keeps all of
|
'both'
|
max_iter
|
int
|
Maximum number of iterations. Each iteration makes at most one forward step and one backward step, and the search stops earlier when no step lowers the criterion. |
100
|
verbose
|
bool
|
Whether to log progress (one INFO message per step and a final summary, through the module logger); nothing is printed. |
True
|
weight_col
|
str
|
Name of a column of |
None
|
Returns:
| Type | Description |
|---|---|
list of str
|
Selected feature list |
Notes
The instance is updated: varlist, tgt_name and the stored training frame are replaced, the standardizer
is refitted on the selected columns when standardize=True, and model is retrained on the selected
features. A candidate whose fit or scoring raises an exception is skipped silently.
Source code in Modeling_Tool/Model/LRM_Tool.py
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 | |
grid_search_params
¶
grid_search_params(data, varlist, tgt_name, eval_sets, param_grid, objective='oot_gap_penalized', primary_set=None, gap_ref_sets=None, metric='auc', refit=True, verbose=True, weight_col=None, eval_weight_col=None)
Grid-search LogisticRegression hyperparameters over a holdout-based objective.
For every combination in param_grid (Cartesian product), a candidate model is
trained on data and scored by AUC on each dataset in eval_sets. The best
combination is chosen by objective (default rewards a high primary-set AUC while
penalizing the train/holdout AUC gap, i.e. overfitting). This is a holdout search
(not k-fold CV), intended for the typical INS/OOS/OOT credit-scoring setup.
When standardize=True on this instance, every candidate inherits the same
standardization config (each candidate fits its own scaler on data), so the
search runs in the same feature space the final (optionally refit) model uses.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame
|
Training dataset (e.g. the in-sample set used for fitting). |
required |
varlist
|
list
|
Feature column names. |
required |
tgt_name
|
str
|
Target column name. |
required |
eval_sets
|
dict of {str: pandas.DataFrame}
|
Ordered mapping of datasets to score by AUC, e.g.
|
required |
param_grid
|
dict of {str: iterable}
|
Hyperparameter search space, e.g. |
required |
objective
|
str or callable
|
How to score each candidate from its per-set AUCs:
|
'oot_gap_penalized'
|
primary_set
|
str
|
Key of |
None
|
gap_ref_sets
|
list of str
|
Set names whose mean AUC forms the gap reference. Defaults to all sets except
|
None
|
metric
|
str
|
Evaluation metric. Currently only |
'auc'
|
refit
|
bool
|
If True, refit |
True
|
verbose
|
bool
|
Print progress / best result. |
True
|
weight_col
|
str
|
Name of a column of |
None
|
eval_weight_col
|
str
|
Name of a column that every dataset in |
None
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
Search results sorted by |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
KeyError
|
If |
Side Effects
Sets self.best_params_ (dict) and self.search_results_ (the returned table),
and merges the best combo into self.params; if refit=True, also retrains
self.model on data.
Examples:
>>> tuner = LRMaster(params={'C': 1.0, 'solver': 'lbfgs'})
>>> res = tuner.grid_search_params(
... data=ins_fit, varlist=woe_cols, tgt_name='bad_flag',
... eval_sets={'ins': ins_woe, 'oos': oos_woe, 'oot': oot_woe},
... param_grid={'C': np.logspace(-3, 2, 31)},
... primary_set='oot', gap_ref_sets=['ins', 'oos'], refit=False,
... )
>>> best_C = tuner.best_params_['C']
Source code in Modeling_Tool/Model/LRM_Tool.py
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 | |
clone
¶
Create a copy of this LRMaster with the same parameters.
The standardization configuration (standardize flag and scaler
prototype) is carried over, but no fitted model or fitted scaler is
copied.
Returns:
| Type | Description |
|---|---|
LRMaster
|
New instance with same params/standardization config but no fitted model |
Source code in Modeling_Tool/Model/LRM_Tool.py
lr_model
¶
Train a Logistic Regression model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mdlx
|
DataFrame or ndarray
|
Training feature matrix |
required |
mdly
|
Series or ndarray
|
Training target variable |
required |
valx
|
DataFrame or ndarray
|
Validation feature matrix (used for reference only: it is accepted for interface symmetry and never read, so
|
required |
valy
|
Series or ndarray
|
Validation target variable (used for reference only: it is accepted for interface symmetry and never read, so
|
required |
params_dict
|
dict
|
Dictionary of parameters for LogisticRegression. |
required |
sample_weight
|
array - like
|
Per-sample weights passed to |
None
|
Returns:
| Type | Description |
|---|---|
LogisticRegression
|
Trained logistic regression model |
Source code in Modeling_Tool/Model/LRM_Tool.py
lr_varimp
¶
Get variable importance from a Logistic Regression model.
Computes the absolute value of the model coefficients as a measure of variable importance.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
LogisticRegression
|
Trained logistic regression model |
required |
Returns:
| Type | Description |
|---|---|
DataFrame
|
DataFrame with columns ['varlist', 'coef', 'importance'] sorted by
importance in descending order. The names in |
Source code in Modeling_Tool/Model/LRM_Tool.py
fast_lr_pvalues
¶
Coefficient p-values for a fitted sklearn LogisticRegression via the
observed Fisher information — same formula as get_lr_statsmodel_summary
but vectorized (no n x n diagonal weight matrix), so it stays O(n*k)
at pipeline sample sizes. Returns a Series indexed by
['Intercept', *feature_names].
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
LogisticRegression
|
Fitted logistic regression model. |
required |
x
|
DataFrame or ndarray
|
Feature matrix whose columns follow the order of the model coefficients. |
required |
feature_names
|
list of str
|
Names of the columns of |
required |
Returns:
| Type | Description |
|---|---|
Series
|
Two-sided p-values of the intercept and of the coefficients, indexed by |
Source code in Modeling_Tool/Model/LRM_Tool.py
get_lr_statsmodel_summary
¶
Generate a statsmodels-style summary for a sklearn LogisticRegression model.
Computes standard errors, z-scores, p-values, and confidence intervals for the logistic regression coefficients using the observed Fisher information matrix.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
LogisticRegression
|
Trained logistic regression model |
required |
x
|
DataFrame or ndarray
|
Feature matrix used for training |
required |
y
|
Series or ndarray
|
Target variable used for training (not used in the computation: the Fisher information depends only on the
predicted probabilities for |
required |
feature_names
|
list of str
|
Feature names (inferred from x if not provided: the columns of |
None
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
Summary table with columns: ['coef', 'std_err', 'z', 'p_value',
'ci_lower', 'ci_upper'], indexed by |
Notes
The weight matrix is a dense n x n array (n is the number of rows), so memory use grows with the square of
the sample size. fast_lr_pvalues returns the same p-values without that matrix.
Source code in Modeling_Tool/Model/LRM_Tool.py
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 | |
compute_aic
¶
Compute AIC (Akaike Information Criterion) for a logistic regression model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
LogisticRegression
|
Fitted logistic regression model |
required |
x
|
DataFrame or ndarray
|
Feature matrix |
required |
y
|
Series or ndarray
|
Target variable |
required |
sample_weight
|
array - like
|
Per-sample weights for log-likelihood / information criteria. |
None
|
Returns:
| Type | Description |
|---|---|
float
|
AIC value (lower is better): |
Source code in Modeling_Tool/Model/LRM_Tool.py
compute_bic
¶
Compute BIC (Bayesian Information Criterion) for a logistic regression model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
LogisticRegression
|
Fitted logistic regression model |
required |
x
|
DataFrame or ndarray
|
Feature matrix |
required |
y
|
Series or ndarray
|
Target variable |
required |
sample_weight
|
array - like
|
Per-sample weights for log-likelihood / information criteria. |
None
|
Returns:
| Type | Description |
|---|---|
float
|
BIC value (lower is better): |
Source code in Modeling_Tool/Model/LRM_Tool.py
Gradient Boosting Models: GBM_Tool¶
GBM_Tool
¶
Gradient Boosting Model Training Toolkit¶
This module provides quick training and evaluation utilities for LightGBM, XGBoost, and CatBoost models, including model training and feature-importance extraction.
Functions:
| Name | Description |
|---|---|
set_num_leaves |
Compute the number of leaves from the maximum depth, to avoid overfitting. |
lgb_model |
Quickly train a LightGBM model. |
lgb_varimp |
Get LightGBM feature importance. |
lgbm_quick_train |
Quickly train a LightGBM model (DataFrame interface). |
xgb_model |
Train an XGBoost model. |
xgb_varimp |
Get XGBoost feature importance. |
xgbm_quick_train |
Quickly train an XGBoost model (DataFrame interface). |
catboost_model |
Train a CatBoost model. |
catboost_varimp |
Get CatBoost feature importance. |
catboost_quick_train |
Quickly train a CatBoost model (DataFrame interface). |
Classes:
| Name | Description |
|---|---|
LightGBMModel |
LightGBM model wrapper class providing a unified training and evaluation interface. |
XGBoostModel |
XGBoost model wrapper class providing a unified training and evaluation interface. |
CatBoostModel |
CatBoost model wrapper class providing a unified training and evaluation interface. |
GradientBoostingModel |
Unified wrapper class that supports switching between LightGBM, XGBoost, and CatBoost. |
Examples:
Functional interface¶
Class-based interface¶
>>> lgb_model = LightGBMModel(params)
>>> lgb_model.fit(x_train, y_train, x_val, y_val)
>>> varimp = lgb_model.get_feature_importance()
Unified interface¶
LightGBMModel
¶
LightGBM model wrapper class.
Provide a unified interface for training, predicting, saving, and loading LightGBM models. Support model calibration, feature-importance retrieval, and more.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
params
|
dict
|
LightGBM model parameter dictionary. |
required |
model
|
LGBMClassifier
|
Preloaded model instance. |
None
|
Attributes:
| Name | Type | Description |
|---|---|---|
params |
dict
|
The parameter dictionary given to the constructor, used by |
model |
LGBMClassifier or None
|
The underlying estimator: the preloaded |
feature_names_ |
list of str or None
|
Column names of the training features, recorded by |
Examples:
>>> lgb_clf = LightGBMModel(params)
>>> lgb_clf.fit(x_train, y_train, x_val, y_val)
>>> preds = lgb_clf.predict(x_test)
Source code in Modeling_Tool/Model/GBM_Tool.py
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 | |
fit
¶
fit(x, y, valx, valy, wgt=None, init_score=None, sample_weight=None, eval_sample_weight=None, eval_init_score=None)
Train the LightGBM model.
Train the model on the training and validation sets, with early stopping support.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
array - like or DataFrame
|
Training-set features. |
required |
y
|
array - like
|
Training-set labels. |
required |
valx
|
array - like or DataFrame
|
Validation-set features. |
required |
valy
|
array - like
|
Validation-set labels. |
required |
wgt
|
array - like
|
Sample weights of the training set. |
None
|
init_score
|
array - like
|
Initial scores (log-odds offset) of the training set. Unless |
None
|
sample_weight
|
array - like
|
Alias of |
None
|
eval_sample_weight
|
array - like
|
Sample weights of the validation set. They weight the validation metric that drives early stopping; with
|
None
|
eval_init_score
|
array - like
|
Initial scores (log-odds offset) of the validation set, so that early stopping measures the combined model. |
None
|
Returns:
| Type | Description |
|---|---|
self
|
The fitted wrapper. |
Notes
params must contain early_stopping_rounds (see lgb_model). Training replaces model; when
x has a columns attribute (a DataFrame) it also sets feature_names_, otherwise feature_names_ is
left as it was.
Source code in Modeling_Tool/Model/GBM_Tool.py
predict
¶
Predict the positive-class probability of each sample.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
array - like or DataFrame
|
Features to predict on. |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
Predicted probabilities. |
Source code in Modeling_Tool/Model/GBM_Tool.py
get_feature_importance
¶
Get the feature importance.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
importance_type
|
str
|
Ignored. It is accepted for API symmetry only: the importance is always the total gain computed by
|
'gain'
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
DataFrame with |
Source code in Modeling_Tool/Model/GBM_Tool.py
save
¶
Save the model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str
|
Path to save the model to. Only the underlying estimator |
required |
Source code in Modeling_Tool/Model/GBM_Tool.py
load
¶
Load the model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str
|
Path to the model file, as written by |
required |
Returns:
| Type | Description |
|---|---|
self
|
The wrapper, with |
Source code in Modeling_Tool/Model/GBM_Tool.py
calibrate
¶
Calibrate the model probabilities.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
array - like
|
Calibration features. |
required |
y
|
array - like
|
Calibration labels. |
required |
method
|
str
|
Calibration method, 'sigmoid' or 'isotonic'. |
'sigmoid'
|
cv
|
str or int
|
Cross-validation strategy passed to |
'prefit'
|
Returns:
| Type | Description |
|---|---|
self
|
The wrapper, whose |
Notes
After calibration model is the CalibratedClassifierCV and not the LightGBM classifier: predict
returns calibrated probabilities, but get_feature_importance no longer works.
Source code in Modeling_Tool/Model/GBM_Tool.py
calibration_curve
¶
Get the calibration curve data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
array - like
|
Features. |
required |
y
|
array - like
|
Labels. |
required |
n_bins
|
int
|
Number of bins. Bins without samples are dropped, so the returned arrays can be shorter than |
10
|
Returns:
| Type | Description |
|---|---|
tuple
|
(fraction_of_positives, mean_predicted_value) |
Source code in Modeling_Tool/Model/GBM_Tool.py
brier_score
¶
Compute the Brier score.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
array - like
|
Features. |
required |
y
|
array - like
|
Labels. |
required |
Returns:
| Type | Description |
|---|---|
float
|
Brier score. |
Source code in Modeling_Tool/Model/GBM_Tool.py
roc_auc
¶
Compute the ROC AUC.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
array - like
|
Features. |
required |
y
|
array - like
|
Labels. |
required |
Returns:
| Type | Description |
|---|---|
float
|
ROC AUC score. |
Source code in Modeling_Tool/Model/GBM_Tool.py
XGBoostModel
¶
XGBoost model wrapper class.
Provide a unified interface for training, predicting, saving, and loading XGBoost models. Support model calibration, feature-importance retrieval, and more.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
params
|
dict
|
XGBoost model parameter dictionary. |
required |
model
|
XGBClassifier
|
Preloaded model instance. |
None
|
Attributes:
| Name | Type | Description |
|---|---|---|
params |
dict
|
The parameter dictionary given to the constructor, used by |
model |
XGBClassifier or None
|
The underlying estimator: the preloaded |
feature_names_ |
list of str or None
|
Column names of the training features, recorded by |
Examples:
>>> xgb_clf = XGBoostModel(params)
>>> xgb_clf.fit(x_train, y_train, x_val, y_val)
>>> preds = xgb_clf.predict(x_test)
Source code in Modeling_Tool/Model/GBM_Tool.py
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 | |
fit
¶
fit(x, y, valx, valy, sample_weight=None, sample_weight_eval_set=None, base_margin=None, eval_base_margin=None)
Train the XGBoost model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
array - like or DataFrame
|
Training-set features. |
required |
y
|
array - like
|
Training-set labels. |
required |
valx
|
array - like or DataFrame
|
Validation-set features. |
required |
valy
|
array - like
|
Validation-set labels. |
required |
sample_weight
|
array - like
|
Sample weights of the training set. |
None
|
sample_weight_eval_set
|
list
|
List of sample weights for the validation set. It holds one array-like, because the single evaluation set
is |
None
|
base_margin
|
array - like
|
Base margin (init_score / log-odds offset) of the training set, used for incremental training (warm start).
Unless |
None
|
eval_base_margin
|
array - like
|
Base margin of the validation set, so that early stopping measures the combined model. |
None
|
Returns:
| Type | Description |
|---|---|
self
|
The fitted wrapper. |
Notes
The eval_metric key of params is dropped (see xgb_model), and early stopping is active only when
params contains early_stopping_rounds. Training replaces model; when x has a columns
attribute (a DataFrame) it also sets feature_names_, otherwise feature_names_ is left as it was.
Source code in Modeling_Tool/Model/GBM_Tool.py
predict
¶
Predict the positive-class probability of each sample.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
array - like or DataFrame
|
Features to predict on. |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
Predicted probabilities. |
Source code in Modeling_Tool/Model/GBM_Tool.py
get_feature_importance
¶
Get the feature importance.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
importance_type
|
str
|
Ignored. It is accepted for API symmetry only: the importance is always the number of splits that use each
feature, as computed by |
'gain'
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
DataFrame with |
Source code in Modeling_Tool/Model/GBM_Tool.py
save
¶
Save the model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str
|
Path to save the model to. Only the underlying estimator |
required |
Source code in Modeling_Tool/Model/GBM_Tool.py
load
¶
Load the model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str
|
Path to the model file, as written by |
required |
Returns:
| Type | Description |
|---|---|
self
|
The wrapper, with |
Source code in Modeling_Tool/Model/GBM_Tool.py
calibrate
¶
Calibrate the model probabilities.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
array - like
|
Calibration features. |
required |
y
|
array - like
|
Calibration labels. |
required |
method
|
str
|
Calibration method, 'sigmoid' or 'isotonic'. |
'sigmoid'
|
cv
|
str or int
|
Cross-validation strategy passed to |
'prefit'
|
Returns:
| Type | Description |
|---|---|
self
|
The wrapper, whose |
Notes
After calibration model is the CalibratedClassifierCV and not the XGBoost classifier: predict
returns calibrated probabilities, but get_feature_importance no longer works.
Source code in Modeling_Tool/Model/GBM_Tool.py
calibration_curve
¶
Get the calibration curve data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
array - like
|
Features. |
required |
y
|
array - like
|
Labels. |
required |
n_bins
|
int
|
Number of bins. Bins without samples are dropped, so the returned arrays can be shorter than |
10
|
Returns:
| Type | Description |
|---|---|
tuple
|
(fraction_of_positives, mean_predicted_value) |
Source code in Modeling_Tool/Model/GBM_Tool.py
brier_score
¶
Compute the Brier score.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
array - like
|
Features. |
required |
y
|
array - like
|
Labels. |
required |
Returns:
| Type | Description |
|---|---|
float
|
Brier score. |
Source code in Modeling_Tool/Model/GBM_Tool.py
roc_auc
¶
Compute the ROC AUC.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
array - like
|
Features. |
required |
y
|
array - like
|
Labels. |
required |
Returns:
| Type | Description |
|---|---|
float
|
ROC AUC score. |
Source code in Modeling_Tool/Model/GBM_Tool.py
CatBoostModel
¶
CatBoost model wrapper class.
Provide a unified interface for training, predicting, saving, and loading CatBoost models. Support model calibration, feature-importance retrieval, and more.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
params
|
dict
|
CatBoost model parameter dictionary. |
required |
model
|
CatBoostClassifier
|
Preloaded model instance. |
None
|
Attributes:
| Name | Type | Description |
|---|---|---|
params |
dict
|
The parameter dictionary given to the constructor, used by |
model |
CatBoostClassifier or None
|
The underlying estimator: the preloaded |
feature_names_ |
list of str or None
|
Column names of the training features, recorded by |
Examples:
>>> cat_clf = CatBoostModel(params)
>>> cat_clf.fit(x_train, y_train, x_val, y_val)
>>> preds = cat_clf.predict(x_test)
Source code in Modeling_Tool/Model/GBM_Tool.py
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 | |
fit
¶
Train the CatBoost model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
array - like or DataFrame
|
Training-set features. |
required |
y
|
array - like
|
Training-set labels. |
required |
valx
|
array - like or DataFrame
|
Validation-set features. |
required |
valy
|
array - like
|
Validation-set labels. |
required |
sample_weight
|
array - like
|
Sample weights of the training set. The validation set is never weighted. |
None
|
Returns:
| Type | Description |
|---|---|
self
|
The fitted wrapper. |
Notes
params is interpreted as in catboost_model (early_stopping_rounds, eval_metric and
cat_features are read from it). Training replaces model; when x has a columns attribute (a
DataFrame) it also sets feature_names_, otherwise feature_names_ is left as it was.
Source code in Modeling_Tool/Model/GBM_Tool.py
predict
¶
Predict the positive-class probability of each sample.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
array - like or DataFrame
|
Features to predict on. |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
Predicted probabilities. |
Source code in Modeling_Tool/Model/GBM_Tool.py
get_feature_importance
¶
Get the feature importance.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
importance_type
|
str
|
Ignored. It is accepted for API symmetry only: the importance is always CatBoost's default
|
'gain'
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
DataFrame with |
Source code in Modeling_Tool/Model/GBM_Tool.py
save
¶
Save the model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str
|
Path to save the model to. Only the underlying estimator |
required |
Source code in Modeling_Tool/Model/GBM_Tool.py
load
¶
Load the model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str
|
Path to the model file, as written by |
required |
Returns:
| Type | Description |
|---|---|
self
|
The wrapper, with |
Source code in Modeling_Tool/Model/GBM_Tool.py
calibrate
¶
Calibrate the model probabilities.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
array - like
|
Calibration features. |
required |
y
|
array - like
|
Calibration labels. |
required |
method
|
str
|
Calibration method, 'sigmoid' or 'isotonic'. |
'sigmoid'
|
cv
|
str or int
|
Cross-validation strategy passed to |
'prefit'
|
Returns:
| Type | Description |
|---|---|
self
|
The wrapper, whose |
Notes
After calibration model is the CalibratedClassifierCV and not the CatBoost classifier: predict
returns calibrated probabilities, but get_feature_importance no longer works.
Source code in Modeling_Tool/Model/GBM_Tool.py
calibration_curve
¶
Get the calibration curve data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
array - like
|
Features. |
required |
y
|
array - like
|
Labels. |
required |
n_bins
|
int
|
Number of bins. Bins without samples are dropped, so the returned arrays can be shorter than |
10
|
Returns:
| Type | Description |
|---|---|
tuple
|
(fraction_of_positives, mean_predicted_value) |
Source code in Modeling_Tool/Model/GBM_Tool.py
brier_score
¶
Compute the Brier score.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
array - like
|
Features. |
required |
y
|
array - like
|
Labels. |
required |
Returns:
| Type | Description |
|---|---|
float
|
Brier score. |
Source code in Modeling_Tool/Model/GBM_Tool.py
roc_auc
¶
Compute the ROC AUC.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
array - like
|
Features. |
required |
y
|
array - like
|
Labels. |
required |
Returns:
| Type | Description |
|---|---|
float
|
ROC AUC score. |
Source code in Modeling_Tool/Model/GBM_Tool.py
GradientBoostingModel
¶
Unified gradient boosting model wrapper class.
Provide one interface for the three frameworks LightGBM, XGBoost, and CatBoost.
The framework is selected with the model_type parameter; the rest of the interface stays the same.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_type
|
str
|
Model type: 'lgb', 'xgb', or 'cat' ('catboost' is an alias). |
required |
params
|
dict
|
Model parameter dictionary. |
required |
Attributes:
| Name | Type | Description |
|---|---|---|
model_type |
str
|
The framework, 'lgb', 'xgb', or 'cat' (the alias 'catboost' is stored as 'cat'). |
params |
dict
|
The parameter dictionary given to the constructor. |
Notes
Attributes that the wrapper does not define are delegated to the fitted underlying estimator, so get_params(),
predict_proba(x) or feature_names_in_ work on a fitted instance as on the original LightGBM / XGBoost /
CatBoost estimator. save and load handle only that estimator, not the wrapper.
Examples:
>>> model = GradientBoostingModel('lgb', params)
>>> model.fit(x_train, y_train, x_val, y_val)
>>> preds = model.predict(x_test)
Incremental learning (warm start)¶
>>> base_margin = init_model.get_base_margin(x_train)
>>> new_model = GradientBoostingModel('xgb', params)
>>> new_model.fit(x_train, y_train, x_val, y_val, init_score=base_margin)
>>> proba = new_model.predict_with_base_margin(
... x_score, init_model.get_base_margin(x_score))
Adapt an already fitted bare estimator (e.g. an XGBClassifier that was pickled directly)¶
>>> init_model = GradientBoostingModel.from_fitted(load_model(path))
>>> init_model.get_base_margin(x_train)
Source code in Modeling_Tool/Model/GBM_Tool.py
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 | |
from_fitted
classmethod
¶
Build a GradientBoostingModel from an already fitted estimator (or wrapper).
Adapt models that were saved historically as bare scikit-learn estimators
(XGBClassifier / LGBMClassifier / CatBoostClassifier) so that they can use the
unified interface, such as :meth:get_base_margin / :meth:predict_with_base_margin,
without retraining.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
object
|
A fitted |
required |
model_type
|
str or None
|
One of 'lgb', 'xgb' or 'cat' ('catboost' is accepted as an alias of 'cat'). If omitted, inferred
automatically from the estimator type. Ignored when |
None
|
params
|
dict
|
Parameter dictionary. If omitted, it is read from the estimator's |
None
|
Returns:
| Type | Description |
|---|---|
GradientBoostingModel
|
A wrapper around the estimator. When |
Raises:
| Type | Description |
|---|---|
ValueError
|
If an unfitted or empty model is passed (a wrapper whose |
Notes
When the feature names can be read from the estimator, they are stored as feature_names_ of the inner
wrapper, and an estimator that lacks feature_names_in_ gets that attribute set when it allows it (a side
effect on the estimator that was passed in).
Source code in Modeling_Tool/Model/GBM_Tool.py
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 | |
fit
¶
fit(x, y, valx, valy, init_score=None, sample_weight=None, eval_sample_weight=None, sample_weight_eval_set=None, eval_init_score=None, **kwargs)
Train the model (supports incremental learning with a warm start).
When init_score is passed, it is used as a log-odds offset and training continues on
the new data: LightGBM uses init_score and XGBoost uses base_margin (the two are
semantically equivalent; this method exposes both uniformly as init_score).
CatBoost does not support init_score.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
array - like or DataFrame
|
Training-set features. |
required |
y
|
array - like
|
Training-set labels. |
required |
valx
|
array - like or DataFrame
|
Validation-set features. |
required |
valy
|
array - like
|
Validation-set labels. |
required |
init_score
|
array - like
|
Initial log-odds offset (the starting point of incremental learning). Usually produced
by the base model's :meth: |
None
|
sample_weight
|
array - like
|
Sample weights of the training set, used by all three frameworks. |
None
|
eval_sample_weight
|
array - like
|
Sample weights of the validation set, which weight the validation metric that drives early
stopping. Used by 'lgb'; for 'xgb' it is passed as |
None
|
sample_weight_eval_set
|
list
|
XGBoost only: list of sample weights for the validation set (one array-like, because there is one
validation set). It takes precedence over |
None
|
eval_init_score
|
array - like
|
Log-odds offset of the validation set (LightGBM |
None
|
**kwargs
|
Remaining keyword arguments are passed through to the |
{}
|
Returns:
| Type | Description |
|---|---|
self
|
The fitted wrapper. |
Raises:
| Type | Description |
|---|---|
NotImplementedError
|
CatBoost does not support incremental learning with |
Notes
By default, as in the existing production workflow, the offset is applied to the training set only.
The validation set receives no offset, so the early-stopping eval metric is evaluated
in the space "without the offset". Pass eval_init_score (the offset of the validation rows) to
evaluate the combined model instead.
Source code in Modeling_Tool/Model/GBM_Tool.py
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 | |
get_base_margin
¶
Return this model's raw log-odds for x (base margin / init score).
Obtain the "raw score before the sigmoid" uniformly across the three frameworks:
- XGBoost:
predict(x, output_margin=True) - LightGBM:
predict(x, raw_score=True) - CatBoost:
predict(x, prediction_type='RawFormulaVal')
The result can be used as the init_score of the next incremental model's :meth:fit,
or fed to :meth:predict_with_base_margin for fused prediction.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
array - like or DataFrame
|
Features to compute the margin for. |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
One-dimensional log-odds array of shape |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If the model has not been trained yet (before |
Source code in Modeling_Tool/Model/GBM_Tool.py
predict_with_base_margin
¶
Fused prediction: sigmoid(base_margin + this model's raw score).
Add the log-odds of a base model (base_margin, usually from
init_model.get_base_margin(x)) to this (incremental) model's own raw score in
log-odds space, then apply the sigmoid. This manual fusion is the only approach that
behaves identically for lgb and xgb, because LightGBM does not support injecting an
init_score at prediction time.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
array - like or DataFrame
|
Features to predict on. |
required |
base_margin
|
array - like
|
Log-odds offset of the base model; its length must match the number of samples in |
required |
return_prob
|
bool
|
If |
True
|
Returns:
| Type | Description |
|---|---|
ndarray
|
One-dimensional array; with |
Source code in Modeling_Tool/Model/GBM_Tool.py
predict
¶
Predict the positive-class probability of each sample.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
array - like or DataFrame
|
Features to predict on. |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
Predicted probabilities of the positive class. |
Source code in Modeling_Tool/Model/GBM_Tool.py
get_feature_importance
¶
Get the feature importance.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
importance_type
|
str
|
Ignored. It is accepted for API symmetry only: each framework returns one fixed kind of importance, the
total gain for 'lgb', the number of splits that use the feature for 'xgb' and CatBoost's default
|
'gain'
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
DataFrame with |
Source code in Modeling_Tool/Model/GBM_Tool.py
save
¶
Save the model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str
|
Path to save the model to. Only the fitted underlying estimator is written, with |
required |
Source code in Modeling_Tool/Model/GBM_Tool.py
load
¶
Load the model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str
|
Path to the model file, as written by |
required |
Returns:
| Type | Description |
|---|---|
self
|
The wrapper, with its underlying estimator replaced by the loaded object. |
Source code in Modeling_Tool/Model/GBM_Tool.py
calibrate
¶
Calibrate the model probabilities.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
array - like
|
Calibration features. |
required |
y
|
array - like
|
Calibration labels. |
required |
method
|
str
|
Calibration method, 'sigmoid' or 'isotonic'. |
'sigmoid'
|
cv
|
str or int
|
Cross-validation strategy passed to |
'prefit'
|
Returns:
| Type | Description |
|---|---|
self
|
The wrapper, whose underlying estimator is now the fitted |
Notes
After calibration the underlying estimator is the CalibratedClassifierCV and not the boosting classifier:
predict returns calibrated probabilities, but get_feature_importance, get_base_margin
and predict_with_base_margin no longer work.
Source code in Modeling_Tool/Model/GBM_Tool.py
brier_score
¶
Compute the Brier score.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
array - like
|
Features. |
required |
y
|
array - like
|
Labels. |
required |
Returns:
| Type | Description |
|---|---|
float
|
Brier score of the predicted positive-class probabilities. |
Source code in Modeling_Tool/Model/GBM_Tool.py
roc_auc
¶
Compute the ROC AUC.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
array - like
|
Features. |
required |
y
|
array - like
|
Labels. |
required |
Returns:
| Type | Description |
|---|---|
float
|
ROC AUC score of the predicted positive-class probabilities. |
Source code in Modeling_Tool/Model/GBM_Tool.py
set_num_leaves
¶
Set the number of leaves from the maximum depth, to avoid overfitting.
Compute a suitable number of leaves from the given maximum depth and weight coefficient. Formula: 2^max_depth - 2^max_depth * wgt
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
max_depth
|
int
|
Maximum depth of the tree. |
5
|
wgt
|
float
|
Weight coefficient, in the range [0, 1]. It is the fraction of the |
1
|
Returns:
| Type | Description |
|---|---|
int
|
Suggested number of leaves (the formula result truncated to an integer). |
Examples:
>>> set_num_leaves(max_depth=5, wgt=0.5)
16
>>> set_num_leaves(max_depth=5) # default wgt=1: 2**5 - 2**5 * 1
0
Source code in Modeling_Tool/Model/GBM_Tool.py
lgb_model
¶
lgb_model(x, y, valx, valy, params_dict, wgt=None, init_score=None, eval_sample_weight=None, eval_init_score=None)
Quickly train a LightGBM model.
Train a LightGBM model on the training and validation sets, with early stopping support.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
array - like or DataFrame
|
Training-set features. |
required |
y
|
array - like
|
Training-set labels. |
required |
valx
|
array - like or DataFrame
|
Validation-set features. |
required |
valy
|
array - like
|
Validation-set labels. |
required |
params_dict
|
dict
|
LightGBM parameter dictionary, passed to |
required |
wgt
|
array - like
|
Sample weights of the training set. |
None
|
init_score
|
array - like
|
Initial scores (log-odds offset) of the training set. Unless |
None
|
eval_sample_weight
|
array - like
|
Sample weights of the validation set. They weight the validation metric that drives early stopping; with
|
None
|
eval_init_score
|
array - like
|
Initial scores (log-odds offset) of the validation set. With it, early stopping measures the combined model
(offset plus trees) instead of the trees alone. |
None
|
Returns:
| Type | Description |
|---|---|
LGBMClassifier
|
The trained LightGBM model. |
Examples:
>>> params = {
... 'n_estimators': 100,
... 'max_depth': 5,
... 'learning_rate': 0.1,
... 'early_stopping_rounds': 20,
... 'eval_metric': 'auc'
... }
>>> model = lgb_model(x_train, y_train, x_val, y_val, params)
Source code in Modeling_Tool/Model/GBM_Tool.py
lgb_varimp
¶
Get the feature importance of a LightGBM model.
Return a DataFrame sorted by feature importance.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
LGBMClassifier
|
The trained LightGBM model. |
required |
Returns:
| Type | Description |
|---|---|
DataFrame
|
DataFrame with |
Examples:
Source code in Modeling_Tool/Model/GBM_Tool.py
lgbm_quick_train
¶
lgbm_quick_train(train_data, validation_data, x, y, params, wgt_col=None, val_wgt_col=None, cat_x_train=None)
Quickly train a LightGBM model (DataFrame interface).
Accept DataFrames for the training and validation sets and extract the features and labels automatically.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
train_data
|
DataFrame
|
Training dataset. |
required |
validation_data
|
DataFrame
|
Validation dataset. |
required |
x
|
list of str
|
List of feature column names. |
required |
y
|
str
|
Name of the target column. |
required |
params
|
dict
|
LightGBM parameter dictionary, passed to |
required |
wgt_col
|
str
|
Name of the sample-weight column of |
None
|
val_wgt_col
|
str
|
Name of the sample-weight column of |
None
|
cat_x_train
|
list of str
|
List of categorical feature column names. Accepted for backward compatibility but currently ignored: the value is never used, so no categorical features are declared. |
None
|
Returns:
| Type | Description |
|---|---|
LGBMClassifier
|
The trained LightGBM model. |
Examples:
>>> model = lgbm_quick_train(
... train_data=train_df,
... validation_data=val_df,
... x=['feat1', 'feat2'],
... y='target',
... params=params_dict
... )
Source code in Modeling_Tool/Model/GBM_Tool.py
xgb_model
¶
xgb_model(x, y, valx, valy, params_dict, sample_weight=None, sample_weight_eval_set=None, base_margin=None, eval_base_margin=None)
Train an XGBoost model.
Train an XGBoost model on the training and validation sets, with early stopping support.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
array - like or DataFrame
|
Training-set features. |
required |
y
|
array - like
|
Training-set labels. |
required |
valx
|
array - like or DataFrame
|
Validation-set features. |
required |
valy
|
array - like
|
Validation-set labels. |
required |
params_dict
|
dict
|
XGBoost parameter dictionary, passed to |
required |
sample_weight
|
array - like
|
Sample weights for the training set. |
None
|
sample_weight_eval_set
|
list
|
List of sample weights for the validation set. It holds one array-like, because the single evaluation set is
|
None
|
base_margin
|
array - like
|
Base margin (initial prediction offset) of the training set. Unless |
None
|
eval_base_margin
|
array - like
|
Base margin of the validation set, so that early stopping measures the combined model (offset plus trees).
|
None
|
Returns:
| Type | Description |
|---|---|
XGBClassifier
|
The trained XGBoost model. |
Notes
The eval_metric key is removed from params_dict before the classifier is built, so a metric given there has
no effect: early stopping uses XGBoost's own default metric for the objective (logloss for the default binary
objective). The model is fitted with verbose=False.
Examples:
>>> params = {
... 'n_estimators': 100,
... 'max_depth': 5,
... 'learning_rate': 0.1,
... 'early_stopping_rounds': 20,
... 'eval_metric': 'auc' # dropped: has no effect on XGBoost
... }
>>> model = xgb_model(x_train, y_train, x_val, y_val, params)
Source code in Modeling_Tool/Model/GBM_Tool.py
xgb_varimp
¶
Get the feature importance of an XGBoost model.
Return a DataFrame sorted by feature importance.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
XGBClassifier
|
The trained XGBoost model. |
required |
Returns:
| Type | Description |
|---|---|
DataFrame
|
DataFrame with |
Examples:
Source code in Modeling_Tool/Model/GBM_Tool.py
xgbm_quick_train
¶
xgbm_quick_train(train_data, validation_data, x, y, wgt_col=None, params=None, sample_weight_eval_set=None, val_wgt_col=None)
Quickly train an XGBoost model (DataFrame interface).
Accept DataFrames for the training and validation sets and extract the features and labels automatically.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
train_data
|
DataFrame
|
Training dataset. |
required |
validation_data
|
DataFrame
|
Validation dataset. |
required |
x
|
list of str
|
List of feature column names. |
required |
y
|
str
|
Name of the target column. |
required |
wgt_col
|
str
|
Name of the sample-weight column of |
None
|
params
|
dict
|
XGBoost parameter dictionary, passed to |
None
|
sample_weight_eval_set
|
list
|
List of sample weights for the validation set. When given, it takes precedence over |
None
|
val_wgt_col
|
str
|
Name of the sample-weight column of |
None
|
Returns:
| Type | Description |
|---|---|
XGBClassifier
|
The trained XGBoost model. |
Examples:
>>> model = xgbm_quick_train(
... train_data=train_df,
... validation_data=val_df,
... x=['feat1', 'feat2'],
... y='target',
... wgt_col='weight',
... params=params_dict
... )
Source code in Modeling_Tool/Model/GBM_Tool.py
catboost_model
¶
Train a CatBoost model.
Train a CatBoost model on the training and validation sets, with early stopping support.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
array - like or DataFrame
|
Training-set features. |
required |
y
|
array - like
|
Training-set labels. |
required |
valx
|
array - like or DataFrame
|
Validation-set features. |
required |
valy
|
array - like
|
Validation-set labels. |
required |
params_dict
|
dict
|
CatBoost parameter dictionary (the aliases n_estimators / max_depth / random_state are supported). The keys
|
required |
sample_weight
|
array - like
|
Sample weights for the training set. The validation set is never weighted. |
None
|
Returns:
| Type | Description |
|---|---|
CatBoostClassifier
|
The trained CatBoost model. |
Notes
params_dict itself is not modified. When absent, loss_function='Logloss' and verbose=False are added to
the CatBoost parameters, and so is allow_writing_files=False unless train_dir is given, so no
catboost_info folder is written by default.
Examples:
>>> params = {
... 'n_estimators': 100,
... 'max_depth': 5,
... 'learning_rate': 0.1,
... 'early_stopping_rounds': 20,
... 'eval_metric': 'AUC'
... }
>>> model = catboost_model(x_train, y_train, x_val, y_val, params)
Source code in Modeling_Tool/Model/GBM_Tool.py
catboost_varimp
¶
Get the feature importance of a CatBoost model.
Return a DataFrame sorted by feature importance.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
CatBoostClassifier
|
The trained CatBoost model. |
required |
Returns:
| Type | Description |
|---|---|
DataFrame
|
DataFrame with |
Examples:
Source code in Modeling_Tool/Model/GBM_Tool.py
catboost_quick_train
¶
catboost_quick_train(train_data, validation_data, x, y, params, wgt_col=None, val_wgt_col=None, cat_features=None)
Quickly train a CatBoost model (DataFrame interface).
Accept DataFrames for the training and validation sets and extract the features and labels automatically.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
train_data
|
DataFrame
|
Training dataset. |
required |
validation_data
|
DataFrame
|
Validation dataset. |
required |
x
|
list of str
|
List of feature column names. |
required |
y
|
str
|
Name of the target column. |
required |
params
|
dict
|
CatBoost parameter dictionary, passed to |
required |
wgt_col
|
str
|
Name of the sample-weight column of |
None
|
val_wgt_col
|
str
|
Name of the validation-set sample-weight column. Accepted for symmetry with |
None
|
cat_features
|
list
|
List of categorical feature column names or indices. It is stored as |
None
|
Returns:
| Type | Description |
|---|---|
CatBoostClassifier
|
The trained CatBoost model. |
Examples:
>>> model = catboost_quick_train(
... train_data=train_df,
... validation_data=val_df,
... x=['feat1', 'feat2'],
... y='target',
... params=params_dict
... )
Source code in Modeling_Tool/Model/GBM_Tool.py
GradientBoostingModel.param_search¶
GBM_Search_Tool attaches param_search to GradientBoostingModel when Modeling_Tool.Model is imported, so the
generated reference above does not list it. It runs a grid or Optuna search over holdout datasets, stores the winning
parameters in best_params_ and the full table in search_results_, and refits the model when refit=True. The
signature, without self:
param_search(data, varlist, tgt_name, eval_sets, search_space, engine='grid', objective='oot_gap_penalized',
primary_set=None, gap_ref_sets=None, metric='auc', validation_set=None, n_trials=50, refit=True,
verbose=True, fit_kwargs=None, random_state=None, weight_col=None, eval_weight_col=None)
See GBM Hyperparameter Search for the arguments and examples. engine='optuna' needs the
optuna extra.
Backward Variable Elimination: Backward_Tool¶
Backward_Tool
¶
Backward Variable Elimination Toolkit (Unified Version)¶
This module provides backward variable elimination based on LightGBM and XGBoost. Variables are screened with a cumulative feature-importance threshold, and post-training performance analysis is supported.
Functions:
| Name | Description |
|---|---|
backward_lgbm |
Run backward variable elimination with a LightGBM model |
backward_xgbm |
Run backward variable elimination with an XGBoost model |
Classes:
| Name | Description |
|---|---|
BackwardVariableEliminator |
Backward variable eliminator supporting LightGBM and XGBoost |
BackwardEliminationAnalyzer |
Analyzer for backward elimination results |
BackwardVariableEliminator
¶
Backward variable eliminator for LightGBM and XGBoost.
Wrap the LightGBM/XGBoost backward variable elimination workflow, with support for multiple elimination rounds and result summaries.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
train_data
|
DataFrame
|
Training dataset. |
required |
varlist
|
list of str
|
Initial list of feature variables. |
required |
dep
|
str
|
Name of the target column. |
required |
model_type
|
str
|
Model type, either "lgbm" (LightGBM) or "xgbm" (XGBoost), compared case-insensitively. Any other value is not rejected: it silently runs XGBoost. |
"lgbm"
|
validation_data
|
DataFrame
|
Validation dataset. |
None
|
test_data_dict
|
dict
|
Dictionary of test datasets. |
None
|
weight_col
|
str
|
Name of the sample-weight column, used for training and for the weighted performance summaries (see
|
None
|
validation_weight_col
|
str
|
Name of the sample-weight column of |
None
|
wgt_col
|
str
|
Alias of |
None
|
Attributes:
| Name | Type | Description |
|---|---|---|
train_data |
DataFrame
|
The training dataset. |
varlist |
list of str
|
The initial list of feature variables. |
dep |
str
|
Name of the target column. |
model_type |
str
|
The model type, converted to lower case. |
validation_data |
DataFrame or None
|
The validation dataset. |
test_data_dict |
dict
|
The test datasets (an empty dict when none were given). |
weight_col |
str or None
|
The sample-weight column ( |
validation_weight_col |
str or None
|
The sample-weight column of the validation dataset. |
Examples:
>>> eliminator = BackwardVariableEliminator(
... train_data=train_df,
... varlist=feature_cols,
... dep='target',
... model_type='lgbm',
... validation_data=val_df
... )
>>> results = eliminator.run(n_rounds=5)
Source code in Modeling_Tool/Model/Backward_Tool.py
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 | |
run
¶
run(n_rounds: int = 5, varreduct_params: Optional[Dict] = None, stopping_metric: str = 'auc', seed: int = 42, num_boost_round: int = 200, early_stopping_rounds: int = 20, importance_type: str = 'gain', cum_importance_threshold: float = 0.99, min_vars: int = 10, ret_perf: bool = True, nbins: int = 10, **kwargs) -> List[Dict]
Run multiple rounds of backward variable elimination.
Every round trains a model on the variables that survived the previous round (the first round uses varlist) with
backward_lgbm or backward_xgbm and keeps the selected variables. The run stops after n_rounds rounds, or
earlier once at most min_vars variables are left. Calling run again discards the previous results.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n_rounds
|
int
|
Number of elimination rounds. |
5
|
varreduct_params
|
dict
|
Model hyperparameters. Every round works on a deep copy, so the caller's dict is not modified. |
None
|
stopping_metric
|
str
|
Early-stopping metric. |
"auc"
|
seed
|
int
|
Random seed. |
42
|
num_boost_round
|
int
|
Maximum number of boosting rounds. |
200
|
early_stopping_rounds
|
int
|
Number of early-stopping rounds. |
20
|
importance_type
|
str
|
Feature importance type. |
"gain"
|
cum_importance_threshold
|
float
|
Cumulative importance threshold. |
0.99
|
min_vars
|
int
|
Minimum number of variables to keep. |
10
|
ret_perf
|
bool
|
Whether to return performance metrics. When False the |
True
|
nbins
|
int
|
Number of bins. |
10
|
**kwargs
|
Further keyword arguments forwarded to |
{}
|
Returns:
| Type | Description |
|---|---|
list of dict
|
Results of each elimination round, also kept by the eliminator. Every dict has the keys |
Source code in Modeling_Tool/Model/Backward_Tool.py
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 | |
get_final_vars
¶
Return the final list of variables after elimination.
Returns:
| Type | Description |
|---|---|
list of str
|
The variables selected by the last round, or |
Source code in Modeling_Tool/Model/Backward_Tool.py
get_summary
¶
Return the summary table of each elimination round.
Returns:
| Type | Description |
|---|---|
DataFrame
|
One row per round with the columns |
Source code in Modeling_Tool/Model/Backward_Tool.py
BackwardEliminationAnalyzer
¶
Analyzer for backward elimination results.
Analyze and visualize the results of a BackwardVariableEliminator run.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
results
|
list of dict
|
Return value of |
required |
Attributes:
| Name | Type | Description |
|---|---|---|
results |
list of dict
|
The results given to the constructor. |
Examples:
>>> analyzer = BackwardEliminationAnalyzer(results)
>>> analyzer.plot_var_reduction()
>>> final_vars = analyzer.get_stable_vars(top_n=20)
Source code in Modeling_Tool/Model/Backward_Tool.py
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 | |
get_stable_vars
¶
Return the stable variables that are kept in every round.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
top_n
|
int
|
Number of stable variables to return (the first N in alphabetical order); None returns all of them. |
None
|
Returns:
| Type | Description |
|---|---|
list of str
|
The variables present in the |
Source code in Modeling_Tool/Model/Backward_Tool.py
plot_var_reduction
¶
Plot a line chart of the number of variables against the elimination round.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
figsize
|
tuple
|
Figure size. |
(8, 4)
|
save_path
|
str
|
File path for saving the figure (written with |
None
|
Returns:
| Type | Description |
|---|---|
None
|
|
Source code in Modeling_Tool/Model/Backward_Tool.py
get_perf_trend
¶
Return the trend of a performance metric over the rounds for a given dataset.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dataset
|
str
|
Dataset name, e.g. "mdl", "hd", "oot": "mdl" is the training data, "hd" the validation data and any other name is
a key of |
"mdl"
|
metric
|
str
|
Name of the performance metric column of the performance summary (for example "IV", "AUC" or "KS"). |
"IV"
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
One row per round that has a performance summary for the dataset, with the columns |
Source code in Modeling_Tool/Model/Backward_Tool.py
backward_lgbm
¶
backward_lgbm(train_data: DataFrame, varlist: List[str], dep: str, varreduct_params: Optional[Dict] = None, stopping_metric: str = 'auc', seed: int = 42, num_boost_round: int = 200, early_stopping_rounds: int = 20, importance_type: str = 'gain', cum_importance_threshold: float = 0.99, min_vars: int = 10, validation_data: Optional[DataFrame] = None, test_data_dict: Optional[Dict[str, DataFrame]] = None, ret_perf: bool = True, nbins: int = 10, precision: int = 5, min_bin_prop: float = 0.05, include_missing: bool = True, equal_freq: bool = True, ascending: bool = True, fillna: Optional[float] = None, spec_values: Optional[List] = None, weight_col: Optional[str] = None, validation_weight_col: Optional[str] = None, wgt_col: Optional[str] = None) -> Tuple
Run backward variable elimination with a LightGBM model.
Train a LightGBM model and screen the variables by a cumulative feature-importance threshold (backward variable elimination).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
train_data
|
DataFrame
|
Training dataset. Must contain the |
required |
varlist
|
list of str
|
List of feature variables used for modeling. |
required |
dep
|
str
|
Name of the target column (binary 0/1 variable). |
required |
varreduct_params
|
dict
|
LightGBM hyperparameter dictionary. Required parameters that are not specified use preset values ( |
None
|
stopping_metric
|
str
|
Evaluation metric for early stopping, e.g. "auc" or "binary_logloss". It is only used when |
"auc"
|
seed
|
int
|
Random seed for reproducibility. It is only used when |
42
|
num_boost_round
|
int
|
Maximum number of boosting rounds. |
200
|
early_stopping_rounds
|
int
|
Number of early-stopping rounds; training stops when the validation metric has not improved for this many consecutive rounds.
The metric is monitored on |
20
|
importance_type
|
str
|
Feature importance type, "gain" or "split". |
"gain"
|
cum_importance_threshold
|
float
|
Cumulative feature-importance threshold. The features are ranked by importance and kept while their cumulative share of the total importance is at most this value (the feature that would push the share above it is not kept). |
0.99
|
min_vars
|
int
|
Minimum number of variables to keep. When fewer variables pass the threshold, the |
10
|
validation_data
|
DataFrame
|
Validation dataset, used for early stopping. It is also scored in the performance summary under the key |
None
|
test_data_dict
|
dict
|
Dictionary of test datasets, in the form |
None
|
ret_perf
|
bool
|
Whether to return model performance metrics. |
True
|
nbins
|
int
|
Number of bins in the Gains table (passed to |
10
|
precision
|
int
|
Numeric precision (performance summary only). |
5
|
min_bin_prop
|
float
|
Minimum bin proportion (performance summary only). |
0.05
|
include_missing
|
bool
|
Whether to include a missing-value bin (performance summary only). |
True
|
equal_freq
|
bool
|
Whether to use equal-frequency binning (performance summary only). |
True
|
ascending
|
bool
|
Not used: accepted for API compatibility and ignored. |
True
|
fillna
|
float
|
Not used: accepted for API compatibility and ignored. |
None
|
spec_values
|
list
|
Not used: accepted for API compatibility and ignored. |
None
|
weight_col
|
str
|
Name of the sample-weight column. It is used as the training weight ( |
None
|
validation_weight_col
|
str
|
Name of the sample-weight column of |
None
|
wgt_col
|
str
|
Alias of |
None
|
Returns:
| Type | Description |
|---|---|
tuple
|
|
Raises:
| Type | Description |
|---|---|
TypeError
|
If the input data is not a |
ImportError
|
If lightgbm is not installed. |
Examples:
>>> selected_vars, model, perf = backward_lgbm(
... train_data=train_df,
... varlist=feature_cols,
... dep='target',
... validation_data=val_df
... )
Source code in Modeling_Tool/Model/Backward_Tool.py
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 | |
backward_xgbm
¶
backward_xgbm(train_data: DataFrame, varlist: List[str], dep: str, varreduct_params: Optional[Dict] = None, stopping_metric: str = 'auc', seed: int = 42, num_boost_round: int = 200, early_stopping_rounds: int = 20, importance_type: str = 'gain', cum_importance_threshold: float = 0.99, min_vars: int = 10, validation_data: Optional[DataFrame] = None, test_data_dict: Optional[Dict[str, DataFrame]] = None, ret_perf: bool = True, nbins: int = 10, precision: int = 5, min_bin_prop: float = 0.05, include_missing: bool = True, equal_freq: bool = True, ascending: bool = True, fillna: Optional[float] = None, spec_values: Optional[List] = None, monotone_constraints: Optional[Dict[str, int]] = None, weight_col: Optional[str] = None, validation_weight_col: Optional[str] = None, wgt_col: Optional[str] = None) -> Tuple
Run backward variable elimination with an XGBoost model.
Train an XGBoost model and screen the variables by a cumulative feature-importance threshold (backward variable elimination).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
train_data
|
DataFrame
|
Training dataset. Must contain the |
required |
varlist
|
list of str
|
List of feature variables used for modeling. |
required |
dep
|
str
|
Name of the target column (binary 0/1 variable). |
required |
varreduct_params
|
dict
|
XGBoost hyperparameter dictionary. Required parameters that are not specified use preset values ( |
None
|
stopping_metric
|
str
|
Evaluation metric for early stopping. It is only used when |
"auc"
|
seed
|
int
|
Random seed. It is only used when |
42
|
num_boost_round
|
int
|
Maximum number of boosting rounds. |
200
|
early_stopping_rounds
|
int
|
Number of early-stopping rounds. The metric is monitored on |
20
|
importance_type
|
str
|
Feature importance type passed to |
"gain"
|
cum_importance_threshold
|
float
|
Cumulative feature-importance threshold. The features are ranked by importance and kept while their cumulative share of the total importance is at most this value (the feature that would push the share above it is not kept). Features that XGBoost never used get an importance of 0. |
0.99
|
min_vars
|
int
|
Minimum number of variables to keep. When fewer variables pass the threshold, the |
10
|
validation_data
|
DataFrame
|
Validation dataset, used for early stopping. It is also scored in the performance summary under the key |
None
|
test_data_dict
|
dict
|
Dictionary of test datasets, in the form |
None
|
ret_perf
|
bool
|
Whether to return performance metrics. |
True
|
nbins
|
int
|
Number of bins in the Gains table (passed to |
10
|
precision
|
int
|
Numeric precision (performance summary only). |
5
|
min_bin_prop
|
float
|
Minimum bin proportion (performance summary only). |
0.05
|
include_missing
|
bool
|
Whether to include a missing-value bin (performance summary only). |
True
|
equal_freq
|
bool
|
Whether to use equal-frequency binning (performance summary only). |
True
|
ascending
|
bool
|
Not used: accepted for API compatibility and ignored. |
True
|
fillna
|
float
|
Not used: accepted for API compatibility and ignored. |
None
|
spec_values
|
list
|
Not used: accepted for API compatibility and ignored. |
None
|
monotone_constraints
|
dict
|
Dictionary of monotone constraints, in the form |
None
|
weight_col
|
str
|
Name of the sample-weight column. It is used as the training weight ( |
None
|
validation_weight_col
|
str
|
Name of the sample-weight column of |
None
|
wgt_col
|
str
|
Alias of |
None
|
Returns:
| Type | Description |
|---|---|
tuple
|
|
Raises:
| Type | Description |
|---|---|
TypeError
|
If the input data is not a |
ImportError
|
If xgboost is not installed. |
Examples:
>>> selected_vars, model, perf = backward_xgbm(
... train_data=train_df,
... varlist=feature_cols,
... dep='target',
... validation_data=val_df
... )
Source code in Modeling_Tool/Model/Backward_Tool.py
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 | |