Modeling_Tool.Feature¶
Feature analysis layer: PSI, IV/KS insights, correlation filtering, unified feature screening, and distribution analysis.
PSICalculator, VarExtractionInsights, and CorrelationFilter are wrappers
The classes you import from Modeling_Tool or Modeling_Tool.Feature are defined in
WOE_Engine_Feature_Patch. They wrap the implementations in
PSI_Tool and Feature_Insights and add the arguments that reuse a fitted WOE engine: binning_engine for
PSICalculator, and woe_engine, woe_binner, and woe_engine_params for VarExtractionInsights and
CorrelationFilter. Every other argument and every method is the one documented for the implementation below.
PSI Population Stability: PSI_Tool¶
PSI_Tool
¶
PSI (Population Stability Index) Calculator Module
This module provides functions and classes for calculating Population Stability Index (PSI) to measure the distribution drift between expected and actual datasets.
Author: Matrix Agent
PSICalculator
¶
A class for calculating Population Stability Index (PSI) with configurable parameters.
This class encapsulates common PSI calculation parameters and provides methods for various PSI calculations including single variable, grouped, and multi-variable comparisons between datasets.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
buckets
|
int
|
Number of bins for binning. Default is 10. |
10
|
equal_freq
|
bool
|
Whether to use equal frequency binning. Default is True. |
True
|
min_bin_prop
|
float
|
Minimum proportion for each bin. Default is 0.05. |
0.05
|
content
|
float
|
Small value to avoid division by zero. Default is 1e-6. |
1e-06
|
precision
|
int
|
Decimal precision for results. Default is 5. |
5
|
missing_policy
|
(drop, include, warn_and_drop)
|
How NaN rows are handled. Default is "include", which routes NaN rows through a dedicated "MISSING" bin
so missing-rate drift contributes to the PSI. See |
"drop"
|
psi_missing_bucket_policy
|
(smooth_laplace, floor_1e6, exclude)
|
How a bin that holds rows on one side only is treated. Default is "smooth_laplace". See |
"smooth_laplace"
|
feature_block_size
|
int or None
|
Number of variables processed per block. Default is 64. This class only validates and stores it (a positive integer or None); it has no effect on the calculation here. |
64
|
Examples:
>>> calculator = PSICalculator(buckets=10, equal_freq=True)
>>> psi = calculator.calculate(expected_df, actual_df, 'score')
Source code in Modeling_Tool/Feature/PSI_Tool.py
80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 | |
calculate
¶
calculate(expected_df: DataFrame, current_data: DataFrame, varlist: List[str], group_by: Optional[str] = None, group_name: Optional[str] = None, return_details=False, missing_policy: Optional[str] = None, psi_missing_bucket_policy: Optional[str] = None) -> DataFrame
Calculate grouped PSI comparing two datasets, using expected as benchmark.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
expected_df
|
DataFrame
|
Expected/baseline dataset. |
required |
current_data
|
DataFrame
|
Actual/comparison dataset. |
required |
varlist
|
list
|
List of variable names. |
required |
group_by
|
str
|
Column to group by in both datasets. Default is None. Legacy argument: without |
None
|
group_name
|
str
|
Specific group column name for multi-group calculation. Default is None. It must be a column of
|
None
|
return_details
|
bool
|
Whether to return detailed bin information. Default is False. If True, a dict |
False
|
missing_policy
|
(drop, include, warn_and_drop)
|
How NaN rows are handled. If None (default), falls back to the value
configured on |
"drop"
|
psi_missing_bucket_policy
|
(smooth_laplace, floor_1e6, exclude)
|
How a bin that holds rows on one side only is treated. If None (default), falls back to the value
configured on |
"smooth_laplace"
|
Returns:
| Type | Description |
|---|---|
DataFrame or dict
|
Grouped PSI results: a DataFrame with the columns |
Source code in Modeling_Tool/Feature/PSI_Tool.py
calculate_psi
¶
calculate_psi(expected: Union[DataFrame, Series], actual: Union[DataFrame, Series], target_col: str, buckets: int = 10, equal_freq: bool = True, group_by: Optional[Union[str, List[str]]] = None, return_details: bool = False, min_bin_prop: float = 0.05, content: float = 1e-06, precision: int = 5, missing_policy: str = 'include', psi_missing_bucket_policy: str = 'smooth_laplace') -> Union[float, DataFrame, Tuple[Dict, Dict]]
Calculate Population Stability Index (PSI) for a variable, optionally by groups.
This function computes PSI to measure the distribution shift between expected (baseline) and actual (comparison) datasets for a specified variable.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
expected
|
DataFrame or Series
|
Expected/baseline data. |
required |
actual
|
DataFrame or Series
|
Actual/comparison data. |
required |
target_col
|
str
|
Column name to calculate PSI for. |
required |
buckets
|
int
|
Number of bins. Default is 10. |
10
|
equal_freq
|
bool
|
Use equal frequency binning. Default is True. |
True
|
group_by
|
str or list
|
Column(s) to group by for stratified PSI calculation. Default is None. |
None
|
return_details
|
bool
|
Return detailed bin information. Default is False. |
False
|
min_bin_prop
|
float
|
Minimum proportion for each bin. Default is 0.05. |
0.05
|
content
|
float
|
Small value to avoid division by zero. Default is 1e-6. |
1e-06
|
precision
|
int
|
Decimal precision. Default is 5. |
5
|
missing_policy
|
(drop, include, warn_and_drop)
|
How NaN rows are handled. Default in 0.5.0 is "include", which routes NaN rows through a dedicated "MISSING" bin so missing-rate drift contributes to the PSI. This is the recommended production behaviour and became the default in 0.5.0 (previously "drop" in 0.4.2 for numeric backward-compat). Pass "drop" to reproduce pre-0.5.0 numbers, or "warn_and_drop" for legacy numbers with a RuntimeWarning naming the NaN counts. |
"drop"
|
psi_missing_bucket_policy
|
(smooth_laplace, floor_1e6, exclude)
|
How a bin that holds rows on one side only is treated. Default is "smooth_laplace": when such a bin
exists, one is added to every bin count before the shares are computed. "floor_1e6" clips the bin shares at
|
"smooth_laplace"
|
Returns:
| Type | Description |
|---|---|
float, pandas.DataFrame, or tuple
|
|
Notes
With group_by, a group that has rows in only one of the two datasets gets the placeholder PSI 999999 (and no
details).
Examples:
>>> # PSI by groups
>>> psi_by_region = calculate_psi(expected_df, actual_df, 'score', group_by='region')
Source code in Modeling_Tool/Feature/PSI_Tool.py
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 | |
calculate_within_psi
¶
calculate_within_psi(data: DataFrame, grp_name: str, target_col: str, benchmark: Optional[Any] = None, equal_freq: bool = True, buckets: int = 10, return_details: bool = False, min_bin_prop: float = 0.05, content: float = 1e-06, precision: int = 5, benchmark_display_name: Optional[str] = None, missing_policy: str = 'include', psi_missing_bucket_policy: str = 'smooth_laplace') -> Union[DataFrame, Dict]
Calculate PSI values within a single dataset, comparing groups to a benchmark.
This function computes PSI between a benchmark group and all other groups in a specified column, useful for monitoring population stability over time.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame
|
Input dataset containing all groups. |
required |
grp_name
|
str
|
Column name for grouping. |
required |
target_col
|
str
|
Column name to calculate PSI for. |
required |
benchmark
|
str or callable
|
Benchmark group value or filter function. Default is None: every group is compared with the whole dataset
(the code does not pick the first group). A callable receives |
None
|
equal_freq
|
bool
|
Use equal frequency binning. Default is True. |
True
|
buckets
|
int
|
Number of bins. Default is 10. |
10
|
return_details
|
bool
|
Return detailed bin information. Default is False. |
False
|
min_bin_prop
|
float
|
Minimum proportion for each bin. Default is 0.05. |
0.05
|
content
|
float
|
Small value to avoid division by zero. Default is 1e-6. |
1e-06
|
precision
|
int
|
Decimal precision. Default is 5. |
5
|
benchmark_display_name
|
str
|
Custom name for benchmark in results. Default is None. When given, the result gets an extra first row with this name and a PSI of 0; otherwise the benchmark group is not listed. |
None
|
missing_policy
|
(drop, include, warn_and_drop)
|
How NaN rows are handled. Default in 0.5.0 is "include", which routes NaN rows through a dedicated "MISSING" bin so missing-rate drift contributes to the PSI. This is the recommended production behaviour and became the default in 0.5.0 (previously "drop" in 0.4.2 for numeric backward-compat). Pass "drop" to reproduce pre-0.5.0 numbers, or "warn_and_drop" for legacy numbers with a RuntimeWarning naming the NaN counts. |
"drop"
|
psi_missing_bucket_policy
|
(smooth_laplace, floor_1e6, exclude)
|
How a bin that holds rows on one side only is treated. Default is "smooth_laplace": when such a bin
exists, one is added to every bin count before the shares are computed. "floor_1e6" clips the bin shares at
|
"smooth_laplace"
|
Returns:
| Type | Description |
|---|---|
DataFrame or dict
|
If return_details is False: DataFrame with a column named as the |
Examples:
>>> # Compare all months against January
>>> psi_results = calculate_within_psi(data, 'month', 'score', benchmark='2024-01')
Source code in Modeling_Tool/Feature/PSI_Tool.py
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 | |
calculate_psi_within_dataset
¶
calculate_psi_within_dataset(data: DataFrame, grp_name: str, varlist: List[str], benchmark: Optional[Any] = None, equal_freq: bool = True, buckets: int = 10, min_bin_prop: float = 0.05, content: float = 1e-06, precision: int = 5, missing_policy: str = 'include', psi_missing_bucket_policy: str = 'smooth_laplace') -> DataFrame
Calculate PSI for multiple variables within a dataset, comparing groups to a benchmark.
This function iterates over a list of variables and calculates PSI for each, combining results into a single DataFrame.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame
|
Input dataset. |
required |
grp_name
|
str
|
Column name for grouping. |
required |
varlist
|
list
|
List of variable names to calculate PSI for. |
required |
benchmark
|
str or callable
|
Benchmark group value or filter function. Default is None: every group is compared with the whole dataset.
A callable receives |
None
|
equal_freq
|
bool
|
Use equal frequency binning. Default is True. |
True
|
buckets
|
int
|
Number of bins. Default is 10. |
10
|
min_bin_prop
|
float
|
Minimum proportion for each bin. Default is 0.05. |
0.05
|
content
|
float
|
Small value to avoid division by zero. Default is 1e-6. |
1e-06
|
precision
|
int
|
Decimal precision. Default is 5. |
5
|
missing_policy
|
(drop, include, warn_and_drop)
|
How NaN rows are handled. Default in 0.5.0 is "include", which routes NaN rows through a dedicated "MISSING" bin so missing-rate drift contributes to the PSI. This is the recommended production behaviour and became the default in 0.5.0 (previously "drop" in 0.4.2 for numeric backward-compat). Pass "drop" to reproduce pre-0.5.0 numbers, or "warn_and_drop" for legacy numbers with a RuntimeWarning naming the NaN counts. |
"drop"
|
psi_missing_bucket_policy
|
(smooth_laplace, floor_1e6, exclude)
|
How a bin that holds rows on one side only is treated. Default is "smooth_laplace": when such a bin
exists, one is added to every bin count before the shares are computed. "floor_1e6" clips the bin shares at
|
"smooth_laplace"
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
Combined PSI results for all variables, sorted by group: a column named as the |
Examples:
>>> variables = ['score', 'age', 'income']
>>> psi_df = calculate_psi_within_dataset(data, 'month', variables, benchmark='2024-01')
Source code in Modeling_Tool/Feature/PSI_Tool.py
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 | |
calculate_multivar_psi_two_sets
¶
calculate_multivar_psi_two_sets(expected_df: DataFrame, actual_df: DataFrame, varlist: List[str], group_by: Optional[Union[str, List[str]]] = None, buckets: int = 10, equal_freq: bool = True, min_bin_prop: float = 0.05, content: float = 1e-06, precision: int = 5, missing_policy: str = 'include', psi_missing_bucket_policy: str = 'smooth_laplace') -> DataFrame
Calculate PSI for multiple variables by comparing two different datasets.
This function computes PSI for each variable in varlist between expected and actual DataFrames.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
expected_df
|
DataFrame
|
Expected/baseline dataset. |
required |
actual_df
|
DataFrame
|
Actual/comparison dataset. |
required |
varlist
|
list
|
List of variable names to calculate PSI for. |
required |
group_by
|
str or list
|
Column(s) to group by. Default is None. |
None
|
buckets
|
int
|
Number of bins. Default is 10. |
10
|
equal_freq
|
bool
|
Use equal frequency binning. Default is True. |
True
|
min_bin_prop
|
float
|
Minimum proportion for each bin. Default is 0.05. |
0.05
|
content
|
float
|
Small value to avoid division by zero. Default is 1e-6. |
1e-06
|
precision
|
int
|
Decimal precision. Default is 5. |
5
|
missing_policy
|
(drop, include, warn_and_drop)
|
How NaN rows are handled. Default in 0.5.0 is "include", which routes NaN rows through a dedicated "MISSING" bin so missing-rate drift contributes to the PSI. This is the recommended production behaviour and became the default in 0.5.0 (previously "drop" in 0.4.2 for numeric backward-compat). Pass "drop" to reproduce pre-0.5.0 numbers, or "warn_and_drop" for legacy numbers with a RuntimeWarning naming the NaN counts. |
"drop"
|
psi_missing_bucket_policy
|
(smooth_laplace, floor_1e6, exclude)
|
How a bin that holds rows on one side only is treated. Default is "smooth_laplace": when such a bin
exists, one is added to every bin count before the shares are computed. "floor_1e6" clips the bin shares at
|
"smooth_laplace"
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
PSI results for all variables with 'var' and 'psi' columns. With |
Examples:
>>> variables = ['score', 'age', 'income']
>>> psi_df = calculate_multivar_psi_two_sets(train_df, production_df, variables)
Source code in Modeling_Tool/Feature/PSI_Tool.py
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 | |
calculate_multigroup_psi_two_sets
¶
calculate_multigroup_psi_two_sets(expected_df: DataFrame, actual_df: DataFrame, varlist: List[str], group_by: Optional[Union[str, List[str]]] = None, buckets: int = 10, equal_freq: bool = True, min_bin_prop: float = 0.05, content: float = 1e-06, precision: int = 5, group_name: Optional[str] = None, return_details: bool = False, missing_policy: str = 'include', psi_missing_bucket_policy: str = 'smooth_laplace') -> Union[DataFrame, Dict[str, DataFrame]]
Calculate grouped PSI using expected DataFrame as benchmark, applied to actual DataFrame groups.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
expected_df
|
DataFrame
|
Expected/baseline dataset. |
required |
actual_df
|
DataFrame
|
Actual/comparison dataset. |
required |
varlist
|
list
|
List of variable names to calculate PSI for. |
required |
group_by
|
str or list
|
Group column name(s); PSI is computed separately for each group. Default is None. Legacy argument: when
|
None
|
buckets
|
int
|
Number of bins. Default is 10. |
10
|
equal_freq
|
bool
|
Whether to use equal-frequency binning. Default is True. |
True
|
min_bin_prop
|
float
|
Minimum proportion for each bin. Default is 0.05. |
0.05
|
content
|
float
|
Small value to avoid division by zero. Default is 1e-6. |
1e-06
|
precision
|
int
|
Decimal precision. Default is 5. |
5
|
group_name
|
str
|
Name of the group column for multi-group calculation. Default is None. When it is given (and |
None
|
return_details
|
bool
|
Whether to return detailed bin information. Default is False. If True, return a dict
{'psi': psi_df, 'details': details_df};
details_df contains the columns: ['bin', 'expected_count', 'actual_count', 'expected_percent',
'actual_percent', 'psi_component', 'bucket_status', 'psi_missing_bucket_policy', group_name, 'var']
(without |
False
|
missing_policy
|
(drop, include, warn_and_drop)
|
How NaN rows are handled. Default in 0.5.0 is "include", which routes NaN rows through a dedicated "MISSING" bin so missing-rate drift contributes to the PSI. This is the recommended production behaviour and became the default in 0.5.0 (previously "drop" in 0.4.2 for numeric backward compatibility). Pass "drop" to reproduce pre-0.5.0 numbers, or "warn_and_drop" to keep the legacy numbers while emitting a RuntimeWarning that reports the NaN counts on both sides. |
"drop"
|
psi_missing_bucket_policy
|
(smooth_laplace, floor_1e6, exclude)
|
How a bin that holds rows on one side only is treated. Default is "smooth_laplace": when such a bin
exists, one is added to every bin count before the shares are computed. "floor_1e6" clips the bin shares at
|
"smooth_laplace"
|
Returns:
| Type | Description |
|---|---|
DataFrame or dict
|
A DataFrame with the columns |
Source code in Modeling_Tool/Feature/PSI_Tool.py
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 | |
Variable Insights and Correlation: Feature_Insights¶
Feature_Insights
¶
Variable extraction and correlation analysis toolkit. Provides variable analysis, IV calculation, WOE plotting, and correlation filtering.
VarExtractionInsights
¶
Variable extraction and insight analyzer.
Analyze the variables of a dataset by computing IV values and WOE bins, with support for plotting and variable screening.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame
|
Input raw DataFrame. |
required |
dep
|
str
|
Column name of the target (dependent) variable. |
required |
plot_path
|
str
|
Directory in which the plots are saved. |
required |
nbins
|
int
|
Number of bins. Default is 10. |
10
|
equal_freq
|
bool
|
Whether to use equal-frequency binning. Default is True. |
True
|
min_bin_prop
|
float
|
Minimum proportion of samples in each bin. Default is 0.05. |
0.05
|
precision
|
int
|
Numeric precision of the WOE and IV calculations. Default is 5. |
5
|
chi2_method
|
bool
|
Whether to use chi-square binning. Default is False. |
False
|
chi2_p
|
float
|
p-value threshold of the chi-square test. Default is 0.9. |
0.9
|
init_equi_bins
|
int
|
Number of initial equal-frequency bins. Default is 5000. |
5000
|
tree_binning
|
bool
|
Whether to use decision-tree binning. Default is True. |
True
|
include_missing
|
bool
|
Whether to treat missing values as a separate bin. Default is True. |
True
|
seed
|
int
|
Random seed. Default is 3407. |
3407
|
missing_rate_ref
|
int / float
|
Reference value used to fill missing values. Default is -999999. |
-999999
|
spec_values
|
list
|
List of special values. Default is an empty list. |
None
|
Examples:
>>> analyzer = VarExtractionInsights(df, 'target', '/path/to/plots')
>>> report = analyzer.get_var_analysis_report(df, ['var1', 'var2'])
Source code in Modeling_Tool/Feature/Feature_Insights.py
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 | |
remove_folder
staticmethod
¶
Delete the specified folder.
Recursively delete the folder at the given path together with all of its contents; do nothing (silently) if the folder does not exist.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file_path
|
str
|
Path of the folder to delete. |
required |
Examples:
Source code in Modeling_Tool/Feature/Feature_Insights.py
get_var_analysis_report
¶
Generate the variable analysis report.
Compute the IV, KS, Lift, and other metrics for the given list of variables and return the analysis summary of the variables that meet the IV threshold.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame
|
Input raw DataFrame. |
required |
varlist
|
list
|
List of variable names to analyze. |
required |
dep
|
str
|
Name of the target column. Default is None (use the dep given at initialization). |
None
|
iv_cut
|
float
|
IV screening threshold. Default is 0.01. |
0.01
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
Summary table of the variable analysis results, with the columns: - var: variable name - n_all: total number of samples - n: number of non-missing samples - ks_in_gains: KS statistic - lift_in_gains: Lift value - iv: IV value - n_bump: number of bins - missing_rate: missing rate - min, mean, max: descriptive statistics - n_bins: number of bins |
Examples:
>>> analyzer = VarExtractionInsights(df, 'target', '/path/to/plots')
>>> report = analyzer.get_var_analysis_report(df, ['var1', 'var2'])
Source code in Modeling_Tool/Feature/Feature_Insights.py
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 | |
plot_woe
¶
Plot the WOE distribution charts.
Compute the WOE values for the given list of variables, plot their distribution charts, and save them to the specified directory.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame
|
Input raw DataFrame. |
required |
varlist
|
list
|
List of variable names to plot. |
required |
plot_group
|
str
|
Name of the grouping variable. Default is None. |
None
|
plot_dirname
|
str
|
Name of the subdirectory in which the plots are saved. Default is "var_analysis_plot". |
'var_analysis_plot'
|
plot_path
|
str
|
Root directory in which the plots are saved. Default is None (use the plot_path given at initialization). |
None
|
Returns:
| Type | Description |
|---|---|
None
|
|
Examples:
>>> analyzer = VarExtractionInsights(df, 'target', '/path/to/plots')
>>> analyzer.plot_woe(df, ['var1', 'var2'])
Source code in Modeling_Tool/Feature/Feature_Insights.py
CorrelationFilter
¶
Correlation filter analyzer.
Provide screening and removal of highly correlated variables based on correlation analysis, with IV comparison and iterative filtering.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame
|
Input raw DataFrame. |
required |
dep
|
str
|
Column name of the target (dependent) variable. |
required |
corr_cutpoint
|
float
|
Correlation coefficient threshold; variable pairs exceeding it are flagged as highly correlated. Default is 0.8. |
0.8
|
method
|
str
|
Method used to compute the correlation coefficients; one of 'pearson', 'spearman', 'kendall'. Default is 'pearson'. |
'pearson'
|
tree_binning
|
bool
|
Whether the IV / KS that decides between correlated variables is computed on decision-tree bins (passed on to
|
False
|
chi2_method
|
bool
|
Whether that IV / KS is computed on chi-square merged bins. |
False
|
seed
|
int
|
Random seed of the binning behind that IV / KS. |
42
|
chi2_p
|
float
|
p-value threshold of the chi-square merging. |
0.999
|
init_equi_bins
|
int
|
Number of initial equal-frequency bins for the chi-square binning. |
1000
|
missing_rate_ref
|
int or float
|
Value that fills missing values before binning. |
-9999999
|
spec_values
|
list
|
Special values (for example |
[]
|
base_metric
|
(iv, ks)
|
Metric (case-insensitive) compared inside a group of correlated variables: the variable with the highest value is kept and the others are removed. |
"iv"
|
Examples:
>>> filter_analyzer = CorrelationFilter(df, 'target')
>>> keep_vars = filter_analyzer.remove_highly_correlated(['var1', 'var2'])
Source code in Modeling_Tool/Feature/Feature_Insights.py
364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 | |
filter_single_iteration
¶
Filter highly correlated variables in a single iteration.
Run one pass of correlation filtering over the variable list, keeping the variable with the highest IV.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
varlist
|
list
|
List of variable names to screen. |
required |
Returns:
| Type | Description |
|---|---|
list
|
List of variable names retained after screening. |
Source code in Modeling_Tool/Feature/Feature_Insights.py
506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 | |
remove_highly_correlated
¶
Iteratively remove highly correlated variables.
Run correlation filtering repeatedly until no variable is removed or the maximum number of iterations is reached.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
varlist
|
list
|
List of variable names to screen. |
required |
max_iterations
|
int
|
Maximum number of iterations. Default is 10. |
10
|
Returns:
| Type | Description |
|---|---|
list
|
List of variable names finally retained. |
Examples:
>>> filter_analyzer = CorrelationFilter(df, 'target')
>>> keep_vars = filter_analyzer.remove_highly_correlated(['var1', 'var2', 'var3'])
Source code in Modeling_Tool/Feature/Feature_Insights.py
calculate_vif
staticmethod
¶
Compute the variance inflation factor (VIF).
Detect multicollinearity by returning the VIF of each variable. The larger the VIF, the more severe the collinearity; a VIF > 10 usually indicates severe collinearity.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DataFrame
|
DataFrame containing the independent variables. |
required |
Returns:
| Type | Description |
|---|---|
DataFrame
|
DataFrame with the following columns: - index: variable name - VIF: variance inflation factor value |
Examples:
>>> vif_result = calculate_vif(X_train)
>>> high_vif_vars = vif_result[vif_result['VIF'] > 10]['index'].tolist()
Source code in Modeling_Tool/Feature/Feature_Insights.py
var_corr_filter
¶
Screen for highly correlated variable pairs.
Compute the correlation coefficients between variables and return the list of highly correlated variable pairs whose correlation exceeds the threshold.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame
|
Input DataFrame. |
required |
varlist
|
list
|
List of variable names to screen. |
required |
corr_cutpoint
|
float
|
Correlation coefficient threshold. Default is 0.8. |
0.8
|
method
|
str
|
Method used to compute the correlation coefficients; one of 'pearson', 'spearman', 'kendall'. Default is 'pearson'. |
'pearson'
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
DataFrame of the highly correlated variable pairs, with the columns: - VAR1: variable 1 - VAR2: variable 2 - CORR: correlation coefficient |
Examples:
Source code in Modeling_Tool/Feature/Feature_Insights.py
WOE-Engine-Aware Classes: WOE_Engine_Feature_Patch¶
The signatures of the three exported classes. Their methods and arguments behave as described in PSI_Tool and
Feature_Insights above.
WOE_Engine_Feature_Patch
¶
WOE-engine-aware wrappers for feature screening tools.
The original Feature modules are compiled in release builds, so mutating their class objects at import time is fragile. These wrappers delegate to the original classes for legacy behavior and only take over when a fitted WOE engine is explicitly supplied.
PSICalculator
¶
Population Stability Index (PSI) calculator that can bin with a fitted WOE engine.
Without binning_engine every call is delegated to Modeling_Tool.Feature.PSI_Tool.PSICalculator: each
variable is binned on the expected sample (equal-frequency or equal-width bins) and the current sample is
cut with the same edges. With a binning_engine the PSI is computed on the bins of that engine instead
(its WOE value is the bin label), so monitoring uses the same mapping as the model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
buckets
|
int
|
Number of bins of the default binning. It has no effect when |
10
|
equal_freq
|
bool
|
Use equal-frequency bins (False gives equal-width bins). It has no effect when |
True
|
min_bin_prop
|
float
|
Minimum proportion for each bin; it caps the number of bins at |
0.05
|
content
|
float
|
Floor of a bin share, so that the logarithm stays finite (see |
1e-06
|
precision
|
int
|
Decimals of the bin edges of the default binning. With |
5
|
binning_engine
|
(WOE_Master, MonotoneWOEBinner, WOEEngineAdapter or None)
|
Fitted WOE engine whose bins define the PSI. |
None
|
missing_policy
|
('include', 'drop', 'warn_and_drop')
|
How NaN rows are handled by the default binning: |
"include"
|
psi_missing_bucket_policy
|
('smooth_laplace', 'floor_1e6', 'exclude')
|
How a bin that holds rows on one side only is treated. |
"smooth_laplace"
|
feature_block_size
|
int or None
|
Number of variables that the engine transforms per block (used only with |
64
|
Attributes:
| Name | Type | Description |
|---|---|---|
buckets, equal_freq, min_bin_prop, content, precision, missing_policy, psi_missing_bucket_policy, feature_block_size |
The constructor values. |
|
binning_engine |
(WOE_Master, MonotoneWOEBinner, WOEEngineAdapter or None)
|
The engine as passed to the constructor. |
Examples:
Source code in Modeling_Tool/Feature/WOE_Engine_Feature_Patch.py
188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 | |
psi_missing_bucket_policy
instance-attribute
¶
calculate
¶
calculate(expected_df, current_data, varlist, group_by=None, group_name=None, return_details=False, missing_policy=None, psi_missing_bucket_policy=None)
Calculate the PSI of each variable between expected_df and current_data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
expected_df
|
DataFrame
|
Expected (baseline) sample. The default binning builds the bins on it. |
required |
current_data
|
DataFrame
|
Current sample that is compared with |
required |
varlist
|
list of str
|
Variables to compute the PSI for. With a |
required |
group_by
|
str, list of str or None
|
Legacy grouping argument. With the default binning it has no effect unless |
None
|
group_name
|
str, list of str or None
|
Column(s) of |
None
|
return_details
|
bool
|
Whether to return the bin-level details together with the PSI table (see Returns). |
False
|
missing_policy
|
('include', 'drop', 'warn_and_drop')
|
How NaN rows are handled by the default binning. |
"include"
|
psi_missing_bucket_policy
|
('smooth_laplace', 'floor_1e6', 'exclude')
|
How a bin that holds rows on one side only is treated. |
"smooth_laplace"
|
Returns:
| Type | Description |
|---|---|
(DataFrame, dict or tuple)
|
The PSI table has one row per variable (and per group value) with the columns
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
KeyError
|
With a |
Notes
With a binning_engine the PSI values are rounded to precision decimals. The default binning does not
round them.
Source code in Modeling_Tool/Feature/WOE_Engine_Feature_Patch.py
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 | |
VarExtractionInsights
¶
Variable insight analyzer: IV, KS and lift per variable, and bivariate WOE charts.
Without an engine the calls are delegated to Modeling_Tool.Feature.Feature_Insights.VarExtractionInsights, which
bins every variable by its own settings (decision-tree bins by default). With woe_binner (a fitted WOE_Master
or MonotoneWOEBinner) or with woe_engine="monotone", the bins and the IV come from that engine instead.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame
|
Input data. It is stored on the instance, and every method takes its own |
required |
dep
|
str
|
Name of the target column (0/1). |
required |
plot_path
|
str or None
|
Root folder of the charts written by |
required |
nbins
|
int
|
Number of bins per variable. |
10
|
equal_freq
|
bool
|
Use equal-frequency bins (False gives equal-width bins). |
True
|
min_bin_prop
|
float
|
Minimum proportion of rows per bin. |
0.05
|
precision
|
int
|
Decimals of the bin edges. |
5
|
chi2_method
|
bool
|
Merge an initial fine binning with a chi-square test. |
False
|
chi2_p
|
float
|
Confidence level of the chi-square merge. |
0.9
|
init_equi_bins
|
int
|
Number of fine bins before the chi-square merge. |
5000
|
tree_binning
|
bool
|
Place the bin edges with a decision tree on the target (supervised bins). |
True
|
include_missing
|
bool
|
Missing values form their own bin. |
True
|
seed
|
int
|
Random seed of the tree binning. |
3407
|
missing_rate_ref
|
int or float
|
Sentinel for missing values. It fills |
-999999
|
spec_values
|
list or None
|
Special values that get their own bins. |
None
|
woe_engine
|
str
|
|
"master"
|
woe_binner
|
(WOE_Master, MonotoneWOEBinner or None)
|
A fitted engine. It is used whenever it is given, whatever |
None
|
woe_engine_params
|
dict or None
|
Constructor arguments of the self-fitted |
None
|
screen_iv_convention
|
('guarded', 'raw')
|
How the IV on the bins of a WOE engine treats a class-pure bin (a bin without bad rows or without good rows,
whose WOE |
"guarded"
|
Attributes:
| Name | Type | Description |
|---|---|---|
data, dep, plot_path, nbins, equal_freq, min_bin_prop, precision, chi2_method, chi2_p, init_equi_bins, tree_binning, include_missing, seed, missing_rate_ref, spec_values, woe_engine, woe_engine_params, screen_iv_convention |
The constructor values. |
|
woe_binner |
(WOE_Master, MonotoneWOEBinner or None)
|
The engine of the constructor, or the self-fitted |
failed_variables |
list of tuple
|
|
iv_sv_pure_bins |
DataFrame
|
The class-pure special-value bins found by the last |
Examples:
>>> insights = VarExtractionInsights(train_df, "bad_flag", None, woe_binner=woe)
>>> report = insights.get_var_analysis_report(train_df, features, iv_cut=0)
Source code in Modeling_Tool/Feature/WOE_Engine_Feature_Patch.py
463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 | |
screen_iv_convention
instance-attribute
¶
remove_folder
staticmethod
¶
Delete the specified folder.
Recursively delete the folder at the given path together with all of its contents; do nothing (silently) if the folder does not exist.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file_path
|
str
|
Path of the folder to delete. |
required |
Source code in Modeling_Tool/Feature/WOE_Engine_Feature_Patch.py
get_var_analysis_report
¶
Compute IV, KS and lift of each variable and return those that reach iv_cut.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame
|
Data that holds the variables and the target column. |
required |
varlist
|
list of str
|
Variables to analyze. |
required |
dep
|
str or None
|
Name of the target column. |
None
|
iv_cut
|
float
|
IV threshold. Variables with |
0.01
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
One row per reported variable with the columns |
Warns:
| Type | Description |
|---|---|
UserWarning
|
If some variables could not be analyzed (they are listed in |
Notes
A constant column is skipped silently. A variable that cannot be binned is left out and recorded in
failed_variables as (name, exception type). With a WOE engine, a variable that is missing from
data is skipped silently, and a variable that the engine was not fitted on is recorded as failed (a
self-fitted MonotoneWOEBinner is fitted once, on the varlist of the first call). The default binning
handles numeric variables only.
Source code in Modeling_Tool/Feature/WOE_Engine_Feature_Patch.py
plot_woe
¶
Plot the bivariate WOE charts of the variables and save them as PNG files.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame
|
Data that holds the variables and the target column (and |
required |
varlist
|
list of str
|
Variables to plot. When the object holds a |
required |
plot_group
|
str or None
|
Name of a grouping column. A chart per variable split by this column is written as well
( |
None
|
plot_dirname
|
str
|
Subdirectory of |
"var_analysis_plot"
|
plot_path
|
str or None
|
Root folder of the charts. |
None
|
Returns:
| Type | Description |
|---|---|
None
|
Saves the images directly. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If no plot path is available ( |
Notes
Only a MonotoneWOEBinner plots from its own bins. Without an engine, or with a WOE_Master as
woe_binner, a new WOE_Master is fitted with the binning settings of the constructor (missing values
are first filled with missing_rate_ref) and the charts are drawn from it.
Source code in Modeling_Tool/Feature/WOE_Engine_Feature_Patch.py
CorrelationFilter
¶
Correlation filter: drop the weaker variable of each highly correlated pair.
Pairs whose absolute correlation exceeds corr_cutpoint are found, and from each group of correlated variables
the one with the highest IV (or KS) is kept. Without an engine the calls are delegated to
Modeling_Tool.Feature.Feature_Insights.CorrelationFilter; with woe_binner (a fitted WOE_Master or
MonotoneWOEBinner) or woe_engine="monotone", the IV and KS come from that engine.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame
|
Input data (raw values). The correlation is computed on the raw values of the numeric variables. |
required |
dep
|
str
|
Name of the target column (0/1). |
required |
corr_cutpoint
|
float
|
Correlation threshold: a pair is correlated when |
0.8
|
method
|
str
|
Correlation method, |
"pearson"
|
tree_binning
|
bool
|
Use decision-tree bins in the default IV and KS computation. Ignored when an engine supplies the bins. |
False
|
chi2_method
|
bool
|
Merge an initial fine binning with a chi-square test in the default computation. With
|
False
|
seed
|
int
|
Random seed of the tree binning. Ignored when an engine supplies the bins. |
42
|
chi2_p
|
float
|
Confidence level of the chi-square merge. |
0.999
|
init_equi_bins
|
int
|
Number of fine bins before the chi-square merge. |
1000
|
missing_rate_ref
|
int or float
|
Sentinel for missing values in the default IV and KS computation. Ignored when an engine supplies the bins. |
-9999999
|
spec_values
|
list
|
Special values (for example |
[]
|
base_metric
|
('iv', 'ks')
|
Metric that decides which variable of a correlated group survives. Any other value raises |
"iv"
|
woe_engine
|
str
|
|
"master"
|
woe_binner
|
(WOE_Master, MonotoneWOEBinner or None)
|
A fitted engine that supplies the IV and KS. It is used whenever it is given, and it also encodes the
non-numeric variables for the correlation. An object of another type raises |
None
|
woe_engine_params
|
dict or None
|
Constructor arguments of the self-fitted |
None
|
screen_iv_convention
|
('guarded', 'raw')
|
How the IV from an engine's bins treats a class-pure bin: |
"guarded"
|
Attributes:
| Name | Type | Description |
|---|---|---|
data, dep, corr_cutpoint, method, tree_binning, chi2_method, seed, chi2_p, init_equi_bins, missing_rate_ref, spec_values, base_metric, woe_engine, woe_binner, woe_engine_params, screen_iv_convention |
The constructor values. |
|
correlated_dict |
dict
|
For each anchor variable of a correlated group, |
filtered_varlist |
list
|
The variables removed by |
Examples:
>>> corr_filter = CorrelationFilter(train_df, "bad_flag", corr_cutpoint=0.7, woe_binner=woe)
>>> keep_vars = corr_filter.remove_highly_correlated(features)
Source code in Modeling_Tool/Feature/WOE_Engine_Feature_Patch.py
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 | |
screen_iv_convention
instance-attribute
¶
calculate_vif
staticmethod
¶
Compute the variance inflation factor (VIF) of each column.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DataFrame
|
DataFrame that holds the independent variables (numeric columns without missing values). |
required |
Returns:
| Type | Description |
|---|---|
DataFrame
|
One row per column of |
Notes
It needs the optional statsmodels package. There is no NaN handling and no weights.
Source code in Modeling_Tool/Feature/WOE_Engine_Feature_Patch.py
filter_single_iteration
¶
Run one pass of the correlation filter over varlist.
From each group of highly correlated variables the one with the highest base_metric is kept and the
others are removed.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
varlist
|
list of str
|
Variables to screen. They must be columns of |
required |
Returns:
| Type | Description |
|---|---|
list of str
|
The retained variables: the winner of each correlated group first (in the order of discovery), followed
by the variables that are not part of any highly correlated pair in their original order. |
Notes
The call updates correlated_dict and the internal decision trace. Non-numeric variables are encoded with
the WOE engine for the correlation when one is available; otherwise they are skipped with a warning and
kept.
Source code in Modeling_Tool/Feature/WOE_Engine_Feature_Patch.py
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 | |
remove_highly_correlated
¶
Iteratively remove highly correlated variables.
Run the correlation filter repeatedly until no variable is removed or the maximum number of iterations is reached.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
varlist
|
list of str
|
Variables to screen. They must be columns of |
required |
max_iterations
|
int
|
Maximum number of filtering passes. |
10
|
Returns:
| Type | Description |
|---|---|
list of str
|
The variables finally retained, with the winner of each correlated group first. |
Notes
filtered_varlist is set to the removed variables, and correlated_dict holds the correlated pairs and
the metric table behind each decision.
Source code in Modeling_Tool/Feature/WOE_Engine_Feature_Patch.py
Unified Feature Screening: Feature_Screen¶
Feature_Screen
¶
Unified feature screening: PSI -> IV -> correlation dedup.
FeatureScreenConfig
dataclass
¶
Settings of :func:feature_screen: the missing-rate, PSI, IV and correlation stages and the optional gates.
The stages run in the order missing rate, PSI, IV, correlation, then the post-selection gates (VIF, group stability,
multi-target, truncation). A stage whose threshold is None or whose switch is off is skipped, and every gate is
off by default. CreditModelPipeline builds this object from its feature_selection dict with
:func:screen_config_from_mapping.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
psi_enabled
|
bool
|
Whether to run the PSI stage, which compares INS with the splits in |
True
|
psi_threshold
|
float
|
A feature is kept when its largest PSI over the compared splits is strictly below this value. |
0.2
|
psi_compare_splits
|
list of str
|
Splits compared with |
['oos']
|
psi_buckets
|
int
|
Number of equal-frequency buckets of the default PSI binning. Only unweighted runs that do not bin PSI on WOE
bins read it; a weighted run without WOE bins takes its PSI bins from |
10
|
psi_use_woe_bins
|
bool
|
Compute PSI on the bins of the screening WOE engine ( |
False
|
iv_enabled
|
bool
|
Whether to run the IV stage. |
True
|
iv_threshold
|
float
|
Lower IV limit: a feature is kept when its IV is at least this value. |
0.02
|
iv_upper_threshold
|
float or None
|
Upper IV limit (gate G02, a leakage guard), on by default since 0.9.3: features whose IV is above it are dropped
and recorded in |
2.0
|
iv_bins
|
int
|
Maximum number of bins of the default IV binning: decision-tree leaves on unweighted runs, weighted equal-frequency bins on weighted runs (which also derive their PSI bins from it). |
10
|
iv_min_bin_prop
|
float
|
Minimum share of rows per bin in the default IV binning of unweighted runs. Weighted runs read |
0.05
|
iv_equal_freq
|
bool
|
Must stay True: the IV binning cannot switch equal-frequency bins off (unweighted runs use decision-tree bins and
weighted runs weighted equal-frequency bins), so any other value raises |
True
|
iv_use_woe_bins
|
bool
|
Compute IV on the bins of the screening WOE engine instead of the default binning. A weighted run that has an engine always bins IV with it. |
False
|
corr_enabled
|
bool
|
Whether to run the correlation stage. |
True
|
corr_threshold
|
float
|
Two features are redundant when the absolute value of their correlation is above this value; of such a group the feature with the higher IV is kept. |
0.75
|
corr_max_iterations
|
int
|
Maximum number of filtering rounds of the correlation stage. |
10
|
corr_use_woe_bins
|
bool
|
Let the screening WOE engine take part in the correlation stage: non-numeric features are WOE-encoded so that they enter the correlation matrix (otherwise they are skipped with a warning and kept), and on unweighted runs the engine's bins also give the IV that decides between two correlated features. |
False
|
corr_method
|
('pearson', 'spearman', 'kendall')
|
Correlation coefficient of the correlation stage. Weighted runs with non-constant weights support Pearson only
( |
"pearson"
|
corr_base_metric
|
('iv', 'ks')
|
Metric that decides which of two correlated features is kept: the higher value wins. |
"iv"
|
corr_nan_policy
|
('pairwise', 'median_fill', 'raise')
|
Missing values in the weighted correlation matrix: |
"pairwise"
|
corr_block_size
|
int
|
Number of feature columns per block of the weighted pairwise correlation matrix. A smaller value lowers peak memory without changing the result; it must be positive. Weighted runs only. |
256
|
on_empty_stage
|
('keep_all_warn', 'keep_all', 'raise')
|
What to do when a stage would drop every feature (each fallback adds a |
"keep_all_warn"
|
missing_rate_threshold
|
float or None
|
Maximum missing rate on INS: features with a higher missing rate are dropped before the PSI stage. |
None
|
missing_rate_ref
|
float or int
|
Value that counts as missing in addition to |
-999999
|
woe_engine
|
str
|
Engine fitted when a |
"equal_freq"
|
woe_fit_query
|
str or None
|
|
None
|
woe_params
|
dict
|
Keyword arguments of |
{'nbins': 10, 'equal_freq': True, 'min_bin_prop': 0.05}
|
monotone_woe_params
|
dict
|
Arguments of the |
{'n_init_bins': 20, 'min_bin_size': 0.03, 'min_n_bins': 2}
|
categorical_features
|
list of str or None
|
Features that a self-fitted monotone engine treats as categorical (only names among the screened features
count). The |
None
|
plot_path
|
str or None
|
Directory for the IV-stage charts. Charts are written to |
None
|
plot_outputs
|
bool
|
Whether to draw the WOE charts of the features that enter the IV stage (needs |
False
|
content
|
float
|
Floor for bin shares that avoids division by zero and |
1e-6
|
precision
|
int
|
Number of decimals to which the weighted equal-frequency bin edges are rounded. Read only by weighted runs that do not use WOE bins. |
5
|
min_bin_prop
|
float
|
Minimum bin share of the weighted equal-frequency bins: it caps their number at |
0.05
|
monthly_iv_min
|
float or None
|
Gate G03 (group stability): minimum IV that a feature must reach in every group of the evidence (for example
every month); a feature whose lowest group IV is below it is dropped. Needs |
None
|
monthly_iv_cv_max
|
float or None
|
G03: maximum coefficient of variation (population standard deviation divided by the mean) of a feature's group
IVs; features above it are dropped, and a zero mean IV counts as an infinite coefficient. Needs
|
None
|
direction_consistency_min
|
float or None
|
G03: minimum share of a feature's groups (those with a non-zero direction) whose direction, the sign of the
association with the target, equals the most common one. Needs |
None
|
min_group_n
|
int or None
|
G03: minimum number of rows for a group to count. |
None
|
insufficient_group_policy
|
('keep_warn', 'drop', 'raise')
|
G03: what to do with a feature that has fewer than two eligible groups: keep it with a warning, drop it, or
raise |
"keep_warn"
|
target_rules
|
('all', 'any', 'min_pass_count')
|
Gate G04 (multi-target): a feature must pass its per-target IV range and direction check on all targets, on any
target, or on at least |
"all"
|
min_pass_count
|
int or None
|
G04: number of targets a feature must pass when |
None
|
per_target_iv_range
|
tuple or dict or None
|
G04: allowed IV range |
None
|
direction_reference_target
|
str or None
|
G04: target whose direction the other targets must not contradict; a target with a different non-zero direction for a feature counts as failed for that feature. |
None
|
max_selected_features
|
int or None
|
Gate G05 (truncation): keep at most this many features, ranked by |
None
|
min_selected_features
|
int or None
|
G05: when fewer features survive the gates, only a warning and a |
None
|
ranking_metric
|
str
|
G05: metric that ranks the features for truncation. Only |
"iv"
|
tie_breaker
|
str
|
G05: how features with equal ranking values are ordered when the cap cuts between them. The only rule is ascending
feature name, so |
"name"
|
vif_enabled
|
bool
|
Gate G06: after the correlation stage, repeatedly drop the feature with the highest VIF until no VIF is above
|
False
|
vif_threshold
|
float
|
G06: the feature with the highest VIF is dropped while that VIF is above this value; an infinite VIF is always dropped. |
10.0
|
vif_min_features
|
int
|
G06: the gate stops dropping when this many features are left, and is skipped (summary note
|
2
|
vif_tie_break_metric
|
str
|
G06: metric that decides among features with an equal VIF; the one with the lower value is dropped first. Only
|
"iv"
|
vif_use_woe_bins
|
bool
|
G06: |
False
|
screen_iv_convention
|
('guarded', 'raw')
|
How the IV on the bins of a WOE engine ( |
"guarded"
|
iv_gap_ratio_warn
|
float
|
Leak warning (0.9.3): a feature with |
2.0
|
iv_gap_abs_warn
|
float
|
Leak warning (0.9.3): flag and warn as above when |
0.5
|
fallback_top_k
|
int
|
Number of features that the empty-stage fallback keeps under |
5
|
Notes
The G03 and G04 settings (monthly_iv_min, monthly_iv_cv_max, direction_consistency_min,
target_rules) need group or per-target evidence that only FeatureValidationPipeline builds. Setting any of
them where no selection_evidence is passed (feature_screen without it, or feature_screen_from_dataframe,
which has no such argument) raises ValueError; inside CreditModelPipeline the error is caught and the whole
screening is skipped (see its feature_selection setting).
Source code in Modeling_Tool/Feature/Feature_Screen.py
90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 | |
screen_config_from_mapping
¶
screen_config_from_mapping(mapping: Mapping[str, Any] | None, *, woe_engine: str | None = None, woe_fit_query: str | None = None, woe_params: Mapping[str, Any] | None = None, monotone_woe_params: Mapping[str, Any] | None = None, plot_path: str | None = None, plot_outputs: bool = False, screen_iv_convention: str | None = None) -> FeatureScreenConfig
Build FeatureScreenConfig from a CM-style feature_selection dict.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mapping
|
Mapping[str, Any] or None
|
|
required |
woe_engine
|
str or None
|
Value of |
None
|
woe_fit_query
|
str or None
|
Value of |
None
|
woe_params
|
Mapping[str, Any] or None
|
Overrides of |
None
|
monotone_woe_params
|
Mapping[str, Any] or None
|
Overrides of |
None
|
plot_path
|
str or None
|
Value of |
None
|
plot_outputs
|
bool
|
Value of |
False
|
screen_iv_convention
|
str or None
|
Value of |
None
|
Returns:
| Type | Description |
|---|---|
FeatureScreenConfig
|
The configuration; its values are not validated here. |
Source code in Modeling_Tool/Feature/Feature_Screen.py
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 | |
fit_screening_woe_engine
¶
fit_screening_woe_engine(train: DataFrame, features: list[str], target_col: str, *, woe_engine: str = 'monotone', woe_fit_query: str | None = None, woe_params: Mapping[str, Any] | None = None, monotone_woe_params: Mapping[str, Any] | None = None, categorical_features: list[str] | None = None) -> Any
Fit a WOE engine on INS for screening steps that reuse bin boundaries.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
train
|
DataFrame
|
INS frame to fit on. It is not modified (a copy is fitted). |
required |
features
|
list of str
|
Features to bin. |
required |
target_col
|
str
|
Binary target column (1 = bad). |
required |
woe_engine
|
str
|
|
"monotone"
|
woe_fit_query
|
str or None
|
|
None
|
woe_params
|
Mapping[str, Any] or None
|
Keyword arguments of |
None
|
monotone_woe_params
|
Mapping[str, Any] or None
|
Arguments of the monotone engine (monotone only): the tuning keys of the |
None
|
categorical_features
|
list of str or None
|
Names among |
None
|
Returns:
| Type | Description |
|---|---|
MonotoneWOEBinner or WOE_Master
|
The fitted engine, ready to be passed to |
Source code in Modeling_Tool/Feature/Feature_Screen.py
535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 | |
feature_screen
¶
feature_screen(splits: dict[str, DataFrame], feature_cols: list[str], target_col: str, *, weight_col: str | None = None, config: FeatureScreenConfig | None = None, prefit_woe_engine: Any | None = None, selection_evidence: Any | None = None) -> FeatureScreenResult
Run PSI -> IV -> correlation screening on pre-split INS/OOS/OOT frames.
The stages run in the order missing rate, PSI, IV, correlation and then the optional gates (VIF, group stability,
multi-target, truncation); a stage that is not configured is skipped. Bins and IV always come from splits["ins"].
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
splits
|
dict of str to pandas.DataFrame
|
Frames keyed |
required |
feature_cols
|
list of str
|
Candidate features, columns of the INS frame. |
required |
target_col
|
str
|
Binary target column (1 = bad), present in the INS frame. |
required |
weight_col
|
str or None
|
Sample-weight column, present in the INS frame and in each compared OOS or OOT frame (finite, non-negative, with
a positive sum; |
None
|
config
|
FeatureScreenConfig or None
|
Screening settings. |
None
|
prefit_woe_engine
|
(WOE_Master, MonotoneWOEBinner or WOEEngineAdapter or None)
|
A fitted WOE engine. On an unweighted run each stage uses it only when its |
None
|
selection_evidence
|
SelectionEvidence or None
|
Evidence for the group-stability (G03) and multi-target (G04) gates. Only |
None
|
Returns:
| Type | Description |
|---|---|
FeatureScreenResult
|
The surviving features ( |
Raises:
| Type | Description |
|---|---|
KeyError
|
If |
ValueError
|
If the weights are invalid, if a G03 or G04 threshold is set without |
EmptyStageError
|
A |
ImportError
|
If |
Warns:
| Type | Description |
|---|---|
UserWarning
|
For each feature that the IV upper limit drops (possible target leakage), for each feature with a large gap
between |
Notes
Four code paths exist. An unweighted run without WOE bins uses PSICalculator, VarExtractionInsights
(decision-tree IV bins) and CorrelationFilter. A weighted run without WOE bins uses weighted equal-frequency
bins and needs numeric features. When a *_use_woe_bins flag is set or a prefit_woe_engine is given, an
unweighted run switches only the flagged stages to the bins of the WOE engine, while a weighted run bins PSI and
IV with the engine. corr_dropped is filled by weighted runs only.
Source code in Modeling_Tool/Feature/Feature_Screen.py
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 | |
feature_screen_from_dataframe
¶
feature_screen_from_dataframe(data: DataFrame, feature_cols: list[str], target_col: str, split_col: str, *, weight_col: str | None = None, config: FeatureScreenConfig | None = None, prefit_woe_engine: Any | None = None) -> FeatureScreenResult
Convenience wrapper that resolves INS/OOS/OOT from a tagged dataframe.
The rows are assigned to the splits by an exact match of split_col with "ins", "oos" and "oot" (rows
with any other value are left out), and the screen then runs as in :func:feature_screen.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame
|
Frame that holds the features, the target and the split column. It is not modified (the splits are copies). |
required |
feature_cols
|
list of str
|
Candidate features. |
required |
target_col
|
str
|
Binary target column (1 = bad). |
required |
split_col
|
str
|
Column whose values |
required |
weight_col
|
str or None
|
Sample-weight column of |
None
|
config
|
FeatureScreenConfig or None
|
Screening settings. |
None
|
prefit_woe_engine
|
(WOE_Master, MonotoneWOEBinner or WOEEngineAdapter or None)
|
A fitted WOE engine, handled as in :func: |
None
|
Returns:
| Type | Description |
|---|---|
FeatureScreenResult
|
The result of :func: |
Raises:
| Type | Description |
|---|---|
KeyError
|
If |
ValueError
|
If no row has |
Notes
This wrapper has no selection_evidence argument, so a config with a G03 or G04 threshold raises
ValueError.
Source code in Modeling_Tool/Feature/Feature_Screen.py
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 | |
Weighted Feature Screening: Weighted_Screen¶
Weighted_Screen
¶
Weighted feature screening: PSI -> IV -> correlation dedup.
WeightedScreenResult
dataclass
¶
Result of :func:weighted_feature_screen and of feature_screen (also exported as FeatureScreenResult).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
selected_features
|
list of str
|
The features that passed every stage. |
required |
iv_table
|
DataFrame
|
IV of the features that entered the IV stage, with the columns |
required |
psi_table
|
DataFrame
|
PSI of the features that entered the PSI stage, with the columns |
required |
corr_dropped
|
DataFrame
|
One row per feature that the correlation stage removed, with the columns |
required |
summary
|
DataFrame
|
One row per stage ( |
required |
missing_rate_table
|
DataFrame
|
Missing rate on INS of every feature that entered the missing-rate stage, with the columns |
empty frame
|
missing_rate_dropped
|
DataFrame
|
The rows of |
empty frame
|
woe_engine
|
object or None
|
The WOE engine that the screen fitted or was given. A |
None
|
woe_engine_meta
|
dict
|
Metadata of the engine: |
{}
|
dropped_detail
|
DataFrame
|
Per-feature drop evidence of the IV upper limit and of the gates, with the columns |
empty frame
|
stage_tables
|
dict of str to pandas.DataFrame
|
Evidence frames of the gates that ran, keyed |
{}
|
Source code in Modeling_Tool/Feature/Weighted_Screen.py
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 | |
EmptyStageError
¶
Bases: ValueError
A screening stage would drop every feature, and the screening must not go on.
Raised when on_empty_stage is "raise", and (since 0.9.3) under the default "keep_all_warn" when every
feature the stage would drop is a hard drop (a leak-gate drop, see HARD_DROP_REASONS), which no fallback may
bring back. It is a ValueError (what the stage raised before), but a distinct type so that a caller which catches
screening failures, such as CreditModelPipeline, can tell this deliberate stop from an unexpected failure.
Source code in Modeling_Tool/Feature/Weighted_Screen.py
hard_dropped_features
¶
The hard drops of a screening: the features that the leak gate dropped, which no empty-stage fallback brings back.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dropped_detail
|
pandas.DataFrame or list of dict or None
|
The |
required |
Returns:
| Type | Description |
|---|---|
dict of str to str
|
Feature -> reason of every row whose reason is in |
Source code in Modeling_Tool/Feature/Weighted_Screen.py
weighted_feature_screen
¶
weighted_feature_screen(data: DataFrame, feature_cols: list[str], target_col: str, split_col: str, weight_col: str | None = None, psi_enabled: bool = True, psi_threshold: float = 0.2, psi_compare_splits: list[str] | None = None, iv_enabled: bool = True, iv_threshold: float = 0.02, corr_enabled: bool = True, corr_threshold: float = 0.75, iv_bins: int = 10, min_bin_prop: float = 0.05, iv_min_bin_prop: float | None = None, corr_max_iterations: int = 10, content: float = 1e-06, precision: int = 5, psi_buckets: int | None = None, plot_path: str | None = None, plot_outputs: bool = False, iv_equal_freq: bool = True, psi_use_woe_bins: bool = False, iv_use_woe_bins: bool = False, corr_use_woe_bins: bool = False, corr_method: str = 'pearson', corr_base_metric: str = 'iv', woe_engine: str = 'equal_freq', woe_fit_query: str | None = None, woe_params: dict[str, Any] | None = None, monotone_woe_params: dict[str, Any] | None = None, prefit_woe_engine: Any | None = None, corr_nan_policy: Literal['pairwise', 'median_fill', 'raise'] = 'pairwise', corr_block_size: int = 256, on_empty_stage: Literal['keep_all_warn', 'keep_all', 'raise'] = 'keep_all_warn', screen_iv_convention: Literal['guarded', 'raw'] = 'guarded', iv_upper_threshold: float | None = DEFAULT_IV_UPPER_THRESHOLD, iv_gap_ratio_warn: float = DEFAULT_IV_GAP_RATIO_WARN, iv_gap_abs_warn: float = DEFAULT_IV_GAP_ABS_WARN, fallback_top_k: int = DEFAULT_FALLBACK_TOP_K) -> WeightedScreenResult
Run PSI -> IV -> correlation screening with optional sample weights.
Bin edges are fit on ins only. When weight_col is None the legacy
unweighted tools are used for backward-compatible results with
CreditModelPipeline (IV uses tree binning via VarExtractionInsights).
Weighted screening uses equal-frequency bins on weighted quantiles.
The function builds a FeatureScreenConfig from its arguments and runs feature_screen_from_dataframe; a
*_use_woe_bins flag or a prefit_woe_engine makes the screen bin with a WOE engine instead.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame
|
Frame that holds the features, the target and the split column. It is not modified. |
required |
feature_cols
|
list of str
|
Candidate features. |
required |
target_col
|
str
|
Binary target column (1 = bad). |
required |
split_col
|
str
|
Column whose values |
required |
weight_col
|
str or None
|
Sample-weight column of |
None
|
psi_enabled
|
bool
|
Whether to run the PSI stage. |
True
|
psi_threshold
|
float
|
A feature is kept when its largest PSI over the compared splits is strictly below this value. |
0.2
|
psi_compare_splits
|
list of str or None
|
Splits compared with |
None
|
iv_enabled
|
bool
|
Whether to run the IV stage. |
True
|
iv_threshold
|
float
|
Features with an IV below this value are dropped. |
0.02
|
corr_enabled
|
bool
|
Whether to run the correlation stage. |
True
|
corr_threshold
|
float
|
Absolute correlation above which two features are redundant; of such a group the feature with the higher IV is kept. |
0.75
|
iv_bins
|
int
|
Maximum number of IV bins (decision-tree leaves on unweighted runs, weighted equal-frequency bins on weighted runs). A weighted run that does not use WOE bins also derives its PSI bins from it. |
10
|
min_bin_prop
|
float
|
Minimum bin share of the weighted equal-frequency bins (it caps their number at |
0.05
|
iv_min_bin_prop
|
float or None
|
Minimum bin share of the IV binning of unweighted runs. |
None
|
corr_max_iterations
|
int
|
Maximum number of filtering rounds of the correlation stage. |
10
|
content
|
float
|
Floor for bin shares that avoids division by zero and |
1e-6
|
precision
|
int
|
Number of decimals to which the weighted equal-frequency bin edges are rounded. |
5
|
psi_buckets
|
int or None
|
Number of equal-frequency buckets of the default PSI binning of unweighted runs. |
None
|
plot_path
|
str or None
|
Directory for the IV-stage charts; used only by unweighted runs together with |
None
|
plot_outputs
|
bool
|
Whether to draw the WOE charts of the features that enter the IV stage into |
False
|
iv_equal_freq
|
bool
|
Must stay True: the IV binning cannot switch equal-frequency bins off (unweighted runs use decision-tree bins and
weighted runs weighted equal-frequency bins), so any other value raises |
True
|
psi_use_woe_bins
|
bool
|
Compute PSI on the bins of the screening WOE engine instead of the default binning. |
False
|
iv_use_woe_bins
|
bool
|
Compute IV on the bins of the screening WOE engine instead of the default binning. |
False
|
corr_use_woe_bins
|
bool
|
Let the screening WOE engine take part in the correlation stage (WOE encoding of non-numeric features, and the IV that decides between correlated features on unweighted runs). |
False
|
corr_method
|
('pearson', 'spearman', 'kendall')
|
Correlation coefficient of the correlation stage (Pearson only with non-constant weights). |
"pearson"
|
corr_base_metric
|
('iv', 'ks')
|
Metric that decides which of two correlated features is kept. |
"iv"
|
woe_engine
|
str
|
Engine fitted when a |
"equal_freq"
|
woe_fit_query
|
str or None
|
|
None
|
woe_params
|
dict or None
|
Keyword arguments of |
None
|
monotone_woe_params
|
dict or None
|
Arguments of the |
None
|
prefit_woe_engine
|
(WOE_Master, MonotoneWOEBinner or WOEEngineAdapter or None)
|
A fitted WOE engine. On an unweighted run a stage uses it only when its |
None
|
corr_nan_policy
|
('pairwise', 'median_fill', 'raise')
|
Missing values in the weighted correlation matrix: |
"pairwise"
|
corr_block_size
|
int
|
Number of feature columns per block of the weighted pairwise correlation matrix; it only limits memory and must be positive. Weighted runs only. |
256
|
on_empty_stage
|
('keep_all_warn', 'keep_all', 'raise')
|
What to do when a stage would drop every feature. |
"keep_all_warn"
|
screen_iv_convention
|
('guarded', 'raw')
|
How the IV on WOE bins treats class-pure bins: |
"guarded"
|
iv_upper_threshold
|
float or None
|
Upper IV limit (gate G02, a leakage guard). The test uses the zero-cell-floored IV and, on WOE bins under the
guarded convention, the larger of it and |
2.0
|
iv_gap_ratio_warn
|
float
|
Warn about a feature, and set its |
2.0
|
iv_gap_abs_warn
|
float
|
Warn about a feature, and set its |
0.5
|
fallback_top_k
|
int
|
Number of features that the empty-stage fallback keeps under |
5
|
Returns:
| Type | Description |
|---|---|
WeightedScreenResult
|
The surviving features with the stage tables and the audit trail. |
Raises:
| Type | Description |
|---|---|
KeyError
|
If |
ValueError
|
If no row has |
Warns:
| Type | Description |
|---|---|
UserWarning
|
For each feature whose |
Notes
missing_rate_threshold, categorical_features and the gate settings (VIF, group stability, multi-target,
truncation) are not exposed here; use feature_screen with a FeatureScreenConfig for them. A weighted run
without WOE bins needs numeric features.
Source code in Modeling_Tool/Feature/Weighted_Screen.py
1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 | |
Distribution Analysis: Distribution_Tool¶
Distribution_Tool
¶
Data processing and analysis toolkit. Provides grouped statistics, distribution analysis, and visualization.
proc_means
¶
Proc Means by Group.
Compute descriptive statistics of numeric variables by grouping variables, including the mean, quantiles, and missing rate.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame
|
Input raw DataFrame. |
required |
varlist
|
list
|
List of numeric variable names to summarize. Non-numeric variables are accepted too: they get |
required |
groupby
|
list
|
List of grouping variable names (a single name as a string is accepted; an empty list or None means no grouping). |
required |
spec_missing_value
|
any
|
Special value to be treated as missing. Default is None. |
None
|
feature_block_size
|
int or None
|
Number of variables described per block, which limits the memory use on wide tables. Default is 128. None
describes all variables in one block. A value that is not a positive integer raises |
128
|
Notes
The special value is replaced by NaN in the whole DataFrame (a copy), including the grouping columns: rows whose
group value equals spec_missing_value fall out of the groups. The input DataFrame itself is not modified.
Examples:
Source code in Modeling_Tool/Feature/Distribution_Tool.py
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 | |
treat_spec_missing
¶
Handle the special missing value.
Replace the value given by self.spec_missing_value with np.nan so that the statistics are computed correctly.
Returns:
| Type | Description |
|---|---|
DataFrame
|
DataFrame after the missing values have been handled. |
Source code in Modeling_Tool/Feature/Distribution_Tool.py
group_means
¶
Compute descriptive statistics by group.
Compute descriptive statistics of the given variables by group, including the count, mean, standard deviation, minimum, maximum, and custom quantiles.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
q
|
list
|
List of quantiles. Default is [0.05, 0.15, 0.25, 0.5, 0.75, 0.95, 0.99]. |
None
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
DataFrame containing the descriptive statistics. |
Source code in Modeling_Tool/Feature/Distribution_Tool.py
group_sum
¶
Compute the number of samples in each group.
Count the observations (total number of samples) in each combination of groups.
Returns:
| Type | Description |
|---|---|
DataFrame
|
Aggregated result containing the number of samples in each group. |
Source code in Modeling_Tool/Feature/Distribution_Tool.py
DistributionShiftAnalyzer
¶
Distribution shift analyzer.
Analyze how the distribution of variables shifts between groups, assessing the difference by comparing the proportion of observations in each group that exceed the outlier threshold of the benchmark group.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame
|
Input raw DataFrame. |
required |
grp_name
|
str
|
Name of the grouping variable. |
required |
benchmark_value
|
any
|
Group value of the benchmark group, used to determine the outlier threshold. |
required |
Examples:
>>> analyzer = DistributionShiftAnalyzer(df, 'gender', 'Male')
>>> result = analyzer.analyze(['age', 'score'])
Source code in Modeling_Tool/Feature/Distribution_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 | |
analyze_single_var
¶
Analyze the distribution shift of a single variable.
Compute, for each group, the proportion of observations that exceed the given quantile threshold of the benchmark group.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
var
|
str
|
Name of the variable to analyze. |
required |
outlier_value
|
float
|
Quantile used to determine the outlier threshold. Default is 0.99. |
0.99
|
Returns:
| Type | Description |
|---|---|
dict
|
Keys are the group values; values are the proportions of observations exceeding the threshold. |
Source code in Modeling_Tool/Feature/Distribution_Tool.py
analyze
¶
Analyze the distribution shift of multiple variables.
For each variable in the list, compute the proportion of observations in each group that exceed the threshold of the benchmark group, and return all results as a DataFrame.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
varlist
|
list
|
List of variable names to analyze. |
required |
outlier_value
|
float
|
Quantile used to determine the outlier threshold. Default is 0.99. |
0.99
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
Rows are indexed by variable name and columns are the group values; each cell is the proportion of observations exceeding the threshold. |
Examples:
>>> analyzer = DistributionShiftAnalyzer(df, 'gender', 'Male')
>>> result = analyzer.analyze(['age', 'score'])
Source code in Modeling_Tool/Feature/Distribution_Tool.py
DistributionPlotter
¶
Distribution plotter.
Visualize the distribution of a numeric variable in several ways; supports kernel density plots, histograms, and rug plots.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame
|
Input DataFrame. |
required |
score
|
str
|
Name of the variable whose distribution is plotted. |
required |
Examples:
>>> plotter = DistributionPlotter(df, 'age')
>>> plotter.plot(method='kdeplot', title='Age Distribution')
Source code in Modeling_Tool/Feature/Distribution_Tool.py
514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 | |
plot_rugplot
¶
Plot a rug plot.
Overlay a rug plot on a kernel density estimate plot to show the density of the data distribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
figsize
|
tuple
|
Figure size. Default is (15, 15). |
(15, 15)
|
title
|
str
|
Figure title. Default is "Distribution Plot". |
'Distribution Plot'
|
Source code in Modeling_Tool/Feature/Distribution_Tool.py
plot_kdeplot
¶
Plot a kernel density estimate.
Show the data distribution with a filled kernel density estimate plot.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
figsize
|
tuple
|
Figure size. Default is (15, 15). |
(15, 15)
|
title
|
str
|
Figure title. Default is "Distribution Plot". |
'Distribution Plot'
|
Source code in Modeling_Tool/Feature/Distribution_Tool.py
plot_displot
¶
Plot a distribution histogram.
Plot a histogram with a kernel density estimate to show the data distribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
figsize
|
tuple
|
Figure size. Default is (15, 15). |
(15, 15)
|
title
|
str
|
Figure title. Default is "Distribution Plot". |
'Distribution Plot'
|
nbins
|
int
|
Number of histogram bins. Default is 10. |
10
|
Source code in Modeling_Tool/Feature/Distribution_Tool.py
plot
¶
Plot the distribution chart.
Plot the distribution of the variable with the specified method.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
method
|
str
|
Plotting method; one of 'rugplot', 'kdeplot' or 'displot'. Default is 'displot'. |
'displot'
|
title
|
str
|
Figure title. Default is "Distribution Plot". |
'Distribution Plot'
|
figsize
|
tuple
|
Figure size. Default is (15, 15). |
(15, 15)
|
nbins
|
int
|
Number of histogram bins (only used by the displot method). Default is 10. |
10
|
Raises:
| Type | Description |
|---|---|
ValueError
|
Raised when an unsupported plotting method is specified. |
Examples:
>>> plotter = DistributionPlotter(df, 'age')
>>> plotter.plot(method='kdeplot', title='Age Distribution')
Source code in Modeling_Tool/Feature/Distribution_Tool.py
proc_means_by_grp
¶
proc_means_by_grp(data, varlist, groupby=None, spec_missing_value=None, q=None, feature_block_size=128)
Compute the variable statistics report by group.
Compute descriptive statistics of the given variables by group and return a report containing the sample count, mean, quantiles, and missing rate. The computation is delegated to the proc_means class.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame
|
Input raw DataFrame. |
required |
varlist
|
list
|
List of numeric variable names to summarize. |
required |
groupby
|
list
|
List of grouping variable names (a single name as a string is accepted). Default is None, which means no grouping (the same as an empty list). |
None
|
spec_missing_value
|
any
|
Special value to be treated as missing. Default is None. It is replaced by NaN in the whole DataFrame, including the grouping columns, so rows whose group value equals it fall out of the groups. |
None
|
q
|
list
|
List of quantiles. Default is [0.05, 0.15, 0.25, 0.5, 0.75, 0.95, 0.99]. |
None
|
feature_block_size
|
int or None
|
Number of variables described per block, which limits the memory use on wide tables. Default is 128. None
describes all variables in one block. A value that is not a positive integer raises |
128
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
Grouped statistics report containing the descriptive statistics of each variable: one row per group value
and variable, with the grouping columns, |
Examples:
Source code in Modeling_Tool/Feature/Distribution_Tool.py
proc_means_for_screening
¶
Build a uniform means table for IV screening reports.
proc_means_by_grp returns object stats (unique/top/freq) when numeric and
categorical columns are melted together. This helper splits by dtype so MIN,
MEAN, and MAX are always present (NaN for non-numeric features).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame
|
Input raw DataFrame. |
required |
varlist
|
list
|
List of variable names to summarize. A name that is not a column of |
required |
spec_missing_value
|
any
|
Special value to be treated as missing. Default is None. |
None
|
q
|
list
|
List of quantiles passed to |
None
|
feature_block_size
|
int or None
|
Number of variables described per block. Default is 128. None describes all variables in one block. |
128
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
One row per variable with the columns |
Source code in Modeling_Tool/Feature/Distribution_Tool.py
get_distribution_shift_single_var
¶
Compute the distribution shift of a single variable.
Analyze, for the given variable, the proportion of observations in each group that exceed the outlier threshold of the benchmark group.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame
|
Input raw DataFrame. |
required |
var
|
str
|
Name of the variable to analyze. |
required |
grp_name
|
str
|
Name of the grouping variable. |
required |
benchmark_value
|
any
|
Group value of the benchmark group. |
required |
outlier_value
|
float
|
Quantile used to determine the outlier threshold. Default is 0.99. |
0.99
|
Returns:
| Type | Description |
|---|---|
dict
|
Keys are the group values; values are the proportions of observations exceeding the threshold. |
Examples:
Source code in Modeling_Tool/Feature/Distribution_Tool.py
get_distribution_shift
¶
Compute the distribution shift of multiple variables.
For each variable in the list, analyze the proportion of observations in each group that exceed the outlier threshold of the benchmark group, and return the transposed DataFrame containing all results.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame
|
Input raw DataFrame. |
required |
varlist
|
list
|
List of variable names to analyze. |
required |
grp_name
|
str
|
Name of the grouping variable. |
required |
benchmark_value
|
any
|
Group value of the benchmark group. |
required |
outlier_value
|
float
|
Quantile used to determine the outlier threshold. Default is 0.99. |
0.99
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
Rows are indexed by variable name and columns are the group values; each cell is the proportion of observations exceeding the threshold. |
Examples:
Source code in Modeling_Tool/Feature/Distribution_Tool.py
plot_distribution
¶
plot_distribution(data, score, method='displot', title='Distribution Plot', figsize=(15, 15), nbins=10)
Plot the distribution chart of a variable.
Plot the distribution of the variable with the specified method; supports kernel density estimate, histogram, and rug plots.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame
|
Input DataFrame. |
required |
score
|
str
|
Name of the variable whose distribution is plotted. |
required |
method
|
str
|
Plotting method; one of 'rugplot', 'kdeplot' or 'displot'. Default is 'displot'. |
'displot'
|
title
|
str
|
Figure title. Default is "Distribution Plot". |
'Distribution Plot'
|
figsize
|
tuple
|
Figure size. Default is (15, 15). |
(15, 15)
|
nbins
|
int
|
Number of histogram bins (only used by the displot method). Default is 10. |
10
|
Returns:
| Type | Description |
|---|---|
None
|
The plot is displayed directly. |
Examples:
>>> plot_distribution(df, 'age', method='kdeplot')
>>> plot_distribution(df, 'score', method='displot', nbins=20)
Source code in Modeling_Tool/Feature/Distribution_Tool.py
ODPS-Side Distribution Analysis: ODPS_Distribution_Tool¶
ODPS_Distribution_Tool
¶
MaxCompute-backed descriptive statistics.
The public proc_means_odps helper keeps the aggregation in MaxCompute and
downloads only the compact aggregate result. PyODPS is imported lazily so the
regular Feature package remains usable without the optional ODPS dependency.
proc_means_odps
¶
proc_means_odps(input_table_name: str, skip_cols: list[str] | None = None, select_cols: list[str] | None = None, batch_size: int = 50, group: str | list[str] | None = None, *, q: list[float] | None = None, quantile_method: Literal['approx', 'exact'] = 'approx', percentile_accuracy: int = 10000, where_clause: str | None = None, spec_missing_value: Any | list[Any] | dict[str, Any] | None = None, include_missing_group: bool = False, sqlrunner: Any | None = None, output_csv: str | Path | None = None, output_table_name: str | None = None, output_table_mode: Literal['overwrite', 'append'] | None = None) -> DataFrame
Calculate numeric descriptive statistics directly in MaxCompute.
batch_size is the number of feature columns included in one aggregate
SQL statement. It does not split or download source-table rows.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_table_name
|
str
|
Table to analyze: |
required |
skip_cols
|
list of str or None
|
Columns excluded from the analyzed variables. They win over |
None
|
select_cols
|
list of str or None
|
Columns to analyze. |
None
|
batch_size
|
int
|
Number of variables per aggregate SQL statement; each batch scans the table once. Must be a positive integer. |
50
|
group
|
str or list of str or None
|
Grouping column(s). |
None
|
q
|
list of float or None
|
Quantile points in |
None
|
quantile_method
|
('approx', 'exact')
|
|
"approx"
|
percentile_accuracy
|
int
|
Accuracy argument of |
10000
|
where_clause
|
str or None
|
One SQL condition, wrapped in parentheses and combined with |
None
|
spec_missing_value
|
number, list of numbers, dict or None
|
Numeric sentinel value(s) turned into NULL before aggregation, so they count neither in |
None
|
include_missing_group
|
bool
|
Whether to keep the groups in which a group column is NULL. By default such rows are left out, as in a pandas
|
False
|
sqlrunner
|
ODPSRunner or None
|
Runner to reuse; it must expose the ODPS client as |
None
|
output_csv
|
str or Path or None
|
Path of a CSV file for the result (without the index); missing parent folders are created. |
None
|
output_table_name
|
str or None
|
MaxCompute table that receives the result; it must differ from |
None
|
output_table_mode
|
('overwrite', 'append')
|
Required with |
"overwrite"
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
One row per variable (and group): the group columns, then |
Raises:
| Type | Description |
|---|---|
ValueError
|
If an argument is invalid (table or column names, |
TypeError
|
If |
ImportError
|
If |
RuntimeError
|
If a batch fails; the message names the batch and its first and last variable, and neither the CSV nor the result table is written. |
Notes
Only numeric variables are analyzed: no UNIQUE, TOP or FREQ is computed for categorical columns.
Source code in Modeling_Tool/Feature/ODPS_Distribution_Tool.py
455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 | |