Modeling_Tool.Model¶
模型训练层 —— LR、LightGBM、XGBoost、后向变量消元。
逻辑回归 — LRM_Tool¶
LRM_Tool
¶
FeatureSelectionAnalyzer
¶
Feature selection analyzer using statistical tests.
Analyzes feature relevance using chi-squared tests, correlation analysis, and variance inflation factor (VIF) for multicollinearity detection.
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
significance_level
|
float
|
Significance level for statistical tests |
0.05
|
示例:
>>> analyzer = FeatureSelectionAnalyzer(significance_level=0.05)
>>> results = analyzer.chi2_selection(train_df, feature_cols, 'target')
>>> vif_df = analyzer.compute_vif(train_df[feature_cols])
源代码位于: Modeling_Tool/Model/LRM_Tool.py
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 | |
chi2_selection
¶
Select features using chi-squared test.
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
data
|
DataFrame
|
Input data |
必需 |
feature_cols
|
list of str
|
Feature column names to evaluate |
必需 |
target_col
|
str
|
Target variable column name |
必需 |
返回:
| 类型 | 描述 |
|---|---|
DataFrame
|
Results with columns ['feature', 'chi2', 'p_value', 'selected'] |
源代码位于: Modeling_Tool/Model/LRM_Tool.py
compute_vif
¶
Compute Variance Inflation Factor (VIF) for multicollinearity detection.
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
data
|
DataFrame
|
Feature matrix (should not include target variable) |
必需 |
返回:
| 类型 | 描述 |
|---|---|
DataFrame
|
DataFrame with columns ['feature', 'VIF'] sorted by VIF descending |
源代码位于: Modeling_Tool/Model/LRM_Tool.py
correlation_filter
¶
Remove highly correlated features.
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
data
|
DataFrame
|
Feature matrix |
必需 |
threshold
|
float
|
Correlation threshold above which features are removed |
0.8
|
返回:
| 类型 | 描述 |
|---|---|
list of str
|
List of features to keep (low correlation subset) |
源代码位于: Modeling_Tool/Model/LRM_Tool.py
LRMaster
¶
Logistic Regression Master Class.
A unified wrapper for logistic regression modeling that encapsulates: - Model training and prediction - Variable importance analysis - Statistical summary generation - Stepwise variable selection - Holdout-based hyperparameter grid search - AIC/BIC calculation - Optional feature standardization (off by default)
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
params
|
dict
|
Parameters for sklearn LogisticRegression, e.g., {'C': 1.0, 'solver': 'lbfgs'} |
None
|
属性:
| 名称 | 类型 | 描述 |
|---|---|---|
params |
dict
|
Model parameters |
model |
LogisticRegression
|
Trained model (None until fit() is called) |
varlist |
list
|
List of feature names |
tgt_name |
str
|
Target variable name |
standardize |
bool
|
Whether feature standardization is enabled |
standardizer |
sklearn-like scaler or None
|
Fitted scaler (None until fit() runs with standardize=True) |
best_params_ |
dict or None
|
Best hyperparameters from grid_search_params (None until it runs) |
search_results_ |
DataFrame or None
|
Full grid_search_params results table (None until it runs) |
示例:
>>> lr = LRMaster(params={'C': 1.0, 'solver': 'lbfgs'})
>>> lr.fit(train_df, ['age', 'income'], 'target')
>>> predictions = lr.predict(test_df)
>>> importance = lr.get_variable_importance()
>>> # With standardization (defaults to StandardScaler)
>>> lr = LRMaster(params={'C': 1.0}, standardize=True)
>>> lr.fit(train_df, ['age', 'income'], 'target')
>>> proba = lr.predict_proba(test_df) # test_df is scaled with the fitted scaler
源代码位于: Modeling_Tool/Model/LRM_Tool.py
373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 | |
set_data
¶
Store reference data for later use (e.g., calibration).
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
data
|
DataFrame
|
Training data to store |
必需 |
返回:
| 类型 | 描述 |
|---|---|
self
|
|
源代码位于: Modeling_Tool/Model/LRM_Tool.py
fit
¶
Train the logistic regression model.
When standardize=True, a scaler is fitted on the training features and
stored as self.standardizer; the model is then trained on the scaled
features. The same scaler is reused at prediction / evaluation time.
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
data
|
DataFrame
|
Training dataset containing features and target |
必需 |
varlist
|
list of str
|
Feature column names to use for training |
必需 |
tgt_name
|
str
|
Target variable column name |
必需 |
val_data
|
DataFrame
|
Validation dataset (currently used for reference; not used in fitting) |
None
|
val_varlist
|
list of str
|
Validation feature column names |
None
|
val_tgt_name
|
str
|
Validation target variable column name |
None
|
weight_col
|
str
|
Column in |
None
|
返回:
| 类型 | 描述 |
|---|---|
self
|
|
源代码位于: Modeling_Tool/Model/LRM_Tool.py
calibrate_model
¶
calibrate_model(model=None, train_df=None, method='sigmoid', cv=5, weight_col=None, sample_weight=None)
Model calibration with optional sample weights.
源代码位于: Modeling_Tool/Model/LRM_Tool.py
eval_calibrated_outcome
¶
Evaluate calibrated vs raw probabilities on a holdout set.
源代码位于: Modeling_Tool/Model/LRM_Tool.py
predict
¶
Predict using the trained model.
When standardization is enabled, the input features are scaled with the
scaler fitted during fit before being passed to the model.
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
data
|
DataFrame
|
Input data for prediction |
必需 |
varlist
|
list
|
Feature names (uses training features if None) |
None
|
返回:
| 类型 | 描述 |
|---|---|
ndarray
|
Predicted class labels |
源代码位于: Modeling_Tool/Model/LRM_Tool.py
predict_proba
¶
Predict class probabilities.
When standardization is enabled, the input features are scaled with the
scaler fitted during fit before being passed to the model.
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
data
|
DataFrame
|
Input data for prediction |
必需 |
varlist
|
list
|
Feature names (uses training features if None) |
None
|
返回:
| 类型 | 描述 |
|---|---|
ndarray
|
Array of shape (n_samples, 2) with class probabilities |
源代码位于: Modeling_Tool/Model/LRM_Tool.py
get_variable_importance
¶
Get variable importance (coefficients) from the model.
返回:
| 类型 | 描述 |
|---|---|
DataFrame
|
DataFrame with columns ['varlist', 'coef', 'importance'] sorted by importance in descending order |
Notes
When standardization is enabled the coefficients are expressed in the standardized feature space (i.e. they are directly comparable in magnitude across features).
源代码位于: Modeling_Tool/Model/LRM_Tool.py
get_statsmodel_summary
¶
Generate a statsmodels-style summary for the trained LR model.
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
data
|
DataFrame
|
Data for computing the summary (uses stored training data if None) |
None
|
varlist
|
list of str
|
Feature names (uses stored varlist if None) |
None
|
tgt_name
|
str
|
Target variable name (uses stored tgt_name if None) |
None
|
返回:
| 类型 | 描述 |
|---|---|
DataFrame
|
Summary table with coefficients, standard errors, z-scores and p-values |
Notes
When standardization is enabled the summary is computed on the standardized feature space, consistent with how the model was trained.
源代码位于: Modeling_Tool/Model/LRM_Tool.py
get_aic
¶
Compute AIC for the trained model.
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
data
|
DataFrame
|
|
None
|
varlist
|
list of str
|
|
None
|
tgt_name
|
str
|
|
None
|
返回:
| 类型 | 描述 |
|---|---|
float
|
|
源代码位于: Modeling_Tool/Model/LRM_Tool.py
get_bic
¶
Compute BIC for the trained model.
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
data
|
DataFrame
|
|
None
|
varlist
|
list of str
|
|
None
|
tgt_name
|
str
|
|
None
|
返回:
| 类型 | 描述 |
|---|---|
float
|
|
源代码位于: Modeling_Tool/Model/LRM_Tool.py
stepwise_selection
¶
stepwise_selection(data, varlist, tgt_name, criterion='aic', direction='both', max_iter=100, verbose=True, weight_col=None)
Perform stepwise variable selection.
Iteratively adds or removes features based on AIC/BIC improvement.
When standardize=True, all interim fits and the final model are
trained on standardized features, and the fitted scaler for the selected
columns is stored on the instance for later prediction.
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
data
|
DataFrame
|
Training data |
必需 |
varlist
|
list of str
|
Initial feature list |
必需 |
tgt_name
|
str
|
Target variable name |
必需 |
criterion
|
str
|
Selection criterion, 'aic' or 'bic' |
'aic'
|
direction
|
str
|
Direction of stepwise selection: 'forward', 'backward', or 'both' |
'both'
|
max_iter
|
int
|
Maximum number of iterations |
100
|
verbose
|
bool
|
Whether to print progress |
True
|
返回:
| 类型 | 描述 |
|---|---|
list of str
|
Selected feature list |
源代码位于: Modeling_Tool/Model/LRM_Tool.py
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 | |
grid_search_params
¶
grid_search_params(data, varlist, tgt_name, eval_sets, param_grid, objective='oot_gap_penalized', primary_set=None, gap_ref_sets=None, metric='auc', refit=True, verbose=True, weight_col=None, eval_weight_col=None)
Grid-search LogisticRegression hyperparameters over a holdout-based objective.
For every combination in param_grid (Cartesian product), a candidate model is
trained on data and scored by AUC on each dataset in eval_sets. The best
combination is chosen by objective (default rewards a high primary-set AUC while
penalizing the train/holdout AUC gap, i.e. overfitting). This is a holdout search
(not k-fold CV), intended for the typical INS/OOS/OOT credit-scoring setup.
When standardize=True on this instance, every candidate inherits the same
standardization config (each candidate fits its own scaler on data), so the
search runs in the same feature space the final (optionally refit) model uses.
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
data
|
DataFrame
|
Training dataset (e.g. the in-sample set used for fitting). |
必需 |
varlist
|
list
|
Feature column names. |
必需 |
tgt_name
|
str
|
Target column name. |
必需 |
eval_sets
|
dict of {str: pandas.DataFrame}
|
Ordered mapping of datasets to score by AUC, e.g.
|
必需 |
param_grid
|
dict of {str: iterable}
|
Hyperparameter search space, e.g. |
必需 |
objective
|
str or callable
|
How to score each candidate from its per-set AUCs:
|
'oot_gap_penalized'
|
primary_set
|
str
|
Key of |
None
|
gap_ref_sets
|
list of str
|
Set names whose mean AUC forms the gap reference. Defaults to all sets except
|
None
|
metric
|
str
|
Evaluation metric. Currently only |
'auc'
|
refit
|
bool
|
If True, refit |
True
|
verbose
|
bool
|
Print progress / best result. |
True
|
返回:
| 类型 | 描述 |
|---|---|
DataFrame
|
Search results sorted by |
Side Effects
Sets self.best_params_ (dict) and self.search_results_ (the returned table),
and merges the best combo into self.params; if refit=True, also retrains
self.model on data.
示例:
>>> tuner = LRMaster(params={'C': 1.0, 'solver': 'lbfgs'})
>>> res = tuner.grid_search_params(
... data=ins_fit, varlist=woe_cols, tgt_name='bad_flag',
... eval_sets={'ins': ins_woe, 'oos': oos_woe, 'oot': oot_woe},
... param_grid={'C': np.logspace(-3, 2, 31)},
... primary_set='oot', gap_ref_sets=['ins', 'oos'], refit=False,
... )
>>> best_C = tuner.best_params_['C']
源代码位于: Modeling_Tool/Model/LRM_Tool.py
1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 | |
clone
¶
Create a copy of this LRMaster with the same parameters.
The standardization configuration (standardize flag and scaler
prototype) is carried over, but no fitted model or fitted scaler is
copied.
返回:
| 类型 | 描述 |
|---|---|
LRMaster
|
New instance with same params/standardization config but no fitted model |
源代码位于: Modeling_Tool/Model/LRM_Tool.py
lr_model
¶
Train a Logistic Regression model.
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
mdlx
|
DataFrame or ndarray
|
Training feature matrix |
必需 |
mdly
|
Series or ndarray
|
Training target variable |
必需 |
valx
|
DataFrame or ndarray
|
Validation feature matrix (used for reference only) |
必需 |
valy
|
Series or ndarray
|
Validation target variable (used for reference only) |
必需 |
params_dict
|
dict
|
Dictionary of parameters for LogisticRegression |
必需 |
sample_weight
|
array - like
|
Per-sample weights passed to |
None
|
返回:
| 类型 | 描述 |
|---|---|
LogisticRegression
|
Trained logistic regression model |
源代码位于: Modeling_Tool/Model/LRM_Tool.py
lr_varimp
¶
Get variable importance from a Logistic Regression model.
Computes the absolute value of the model coefficients as a measure of variable importance.
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
model
|
LogisticRegression
|
Trained logistic regression model |
必需 |
返回:
| 类型 | 描述 |
|---|---|
DataFrame
|
DataFrame with columns ['varlist', 'coef', 'importance'] sorted by importance in descending order |
源代码位于: Modeling_Tool/Model/LRM_Tool.py
get_lr_statsmodel_summary
¶
Generate a statsmodels-style summary for a sklearn LogisticRegression model.
Computes standard errors, z-scores, p-values, and confidence intervals for the logistic regression coefficients using the observed Fisher information matrix.
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
model
|
LogisticRegression
|
Trained logistic regression model |
必需 |
x
|
DataFrame or ndarray
|
Feature matrix used for training |
必需 |
y
|
Series or ndarray
|
Target variable used for training |
必需 |
feature_names
|
list of str
|
Feature names (inferred from x if not provided) |
None
|
返回:
| 类型 | 描述 |
|---|---|
DataFrame
|
Summary table with columns: ['coef', 'std_err', 'z', 'p_value', 'ci_lower', 'ci_upper'] |
源代码位于: Modeling_Tool/Model/LRM_Tool.py
compute_aic
¶
Compute AIC (Akaike Information Criterion) for a logistic regression model.
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
model
|
LogisticRegression
|
Fitted logistic regression model |
必需 |
x
|
DataFrame or ndarray
|
Feature matrix |
必需 |
y
|
Series or ndarray
|
Target variable |
必需 |
sample_weight
|
array - like
|
Per-sample weights for log-likelihood / information criteria. |
None
|
返回:
| 类型 | 描述 |
|---|---|
float
|
AIC value (lower is better) |
源代码位于: Modeling_Tool/Model/LRM_Tool.py
compute_bic
¶
Compute BIC (Bayesian Information Criterion) for a logistic regression model.
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
model
|
LogisticRegression
|
Fitted logistic regression model |
必需 |
x
|
DataFrame or ndarray
|
Feature matrix |
必需 |
y
|
Series or ndarray
|
Target variable |
必需 |
sample_weight
|
array - like
|
Per-sample weights for log-likelihood / information criteria. |
None
|
返回:
| 类型 | 描述 |
|---|---|
float
|
BIC value (lower is better) |
源代码位于: Modeling_Tool/Model/LRM_Tool.py
梯度提升模型 — GBM_Tool¶
GBM_Tool
¶
梯度提升模型训练工具包¶
本模块提供LightGBM、XGBoost和CatBoost模型的快速训练和评估功能, 包括模型训练、特征重要性提取等常用操作。
函数:
| 名称 | 描述 |
|---|---|
set_num_leaves |
根据最大深度计算叶子节点数,避免过拟合。 |
lgb_model |
快速训练LightGBM模型。 |
lgb_varimp |
获取LightGBM特征重要性。 |
lgbm_quick_train |
快速训练LightGBM模型(使用DataFrame接口)。 |
xgb_model |
训练XGBoost模型。 |
xgb_varimp |
获取XGBoost特征重要性。 |
xgbm_quick_train |
快速训练XGBoost模型(使用DataFrame接口)。 |
catboost_model |
训练CatBoost模型。 |
catboost_varimp |
获取CatBoost特征重要性。 |
catboost_quick_train |
快速训练CatBoost模型(使用DataFrame接口)。 |
类:
| 名称 | 描述 |
|---|---|
LightGBMModel |
LightGBM模型封装类,提供统一的训练和评估接口。 |
XGBoostModel |
XGBoost模型封装类,提供统一的训练和评估接口。 |
CatBoostModel |
CatBoost模型封装类,提供统一的训练和评估接口。 |
GradientBoostingModel |
统一封装类,支持LightGBM、XGBoost和CatBoost切换。 |
示例:
函数式调用¶
类封装调用¶
>>> lgb_model = LightGBMModel(params)
>>> lgb_model.fit(x_train, y_train, x_val, y_val)
>>> varimp = lgb_model.get_feature_importance()
统一接口调用¶
LightGBMModel
¶
LightGBM模型封装类。
提供统一的LightGBM模型训练、预测、保存和加载接口。 支持模型校准、特征重要性获取等功能。
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
params
|
dict
|
LightGBM模型参数字典 |
必需 |
model
|
LGBMClassifier
|
预加载的模型实例 |
None
|
示例:
>>> lgb_clf = LightGBMModel(params)
>>> lgb_clf.fit(x_train, y_train, x_val, y_val)
>>> preds = lgb_clf.predict(x_test)
源代码位于: Modeling_Tool/Model/GBM_Tool.py
642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 | |
fit
¶
训练LightGBM模型。
使用训练集和验证集训练模型,支持早停机制。
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
x
|
array - like or DataFrame
|
训练集特征 |
必需 |
y
|
array - like
|
训练集标签 |
必需 |
valx
|
array - like or DataFrame
|
验证集特征 |
必需 |
valy
|
array - like
|
验证集标签 |
必需 |
wgt
|
array - like
|
样本权重 |
None
|
init_score
|
array - like
|
初始化分数 |
None
|
返回:
| 类型 | 描述 |
|---|---|
self
|
|
源代码位于: Modeling_Tool/Model/GBM_Tool.py
predict
¶
预测样本的概率。
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
x
|
array - like or DataFrame
|
预测特征 |
必需 |
返回:
| 类型 | 描述 |
|---|---|
ndarray
|
预测概率 |
get_feature_importance
¶
获取特征重要性。
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
importance_type
|
str
|
特征重要性类型,可选 'gain' 或 'split' |
'gain'
|
返回:
| 类型 | 描述 |
|---|---|
DataFrame
|
包含 feature 和 importance 列的DataFrame |
源代码位于: Modeling_Tool/Model/GBM_Tool.py
save
¶
load
¶
calibrate
¶
模型概率校准。
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
x
|
array - like
|
校准特征 |
必需 |
y
|
array - like
|
校准标签 |
必需 |
method
|
str
|
校准方法,'sigmoid' 或 'isotonic' |
'sigmoid'
|
cv
|
str or int
|
交叉验证方式 |
'prefit'
|
返回:
| 类型 | 描述 |
|---|---|
self
|
|
源代码位于: Modeling_Tool/Model/GBM_Tool.py
calibration_curve
¶
获取校准曲线数据。
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
x
|
array - like
|
特征 |
必需 |
y
|
array - like
|
标签 |
必需 |
n_bins
|
int
|
分箱数 |
10
|
返回:
| 类型 | 描述 |
|---|---|
tuple
|
(fraction_of_positives, mean_predicted_value) |
源代码位于: Modeling_Tool/Model/GBM_Tool.py
brier_score
¶
计算Brier分数。
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
x
|
array - like
|
特征 |
必需 |
y
|
array - like
|
标签 |
必需 |
返回:
| 类型 | 描述 |
|---|---|
float
|
Brier分数 |
源代码位于: Modeling_Tool/Model/GBM_Tool.py
roc_auc
¶
计算ROC AUC。
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
x
|
array - like
|
特征 |
必需 |
y
|
array - like
|
标签 |
必需 |
返回:
| 类型 | 描述 |
|---|---|
float
|
ROC AUC分数 |
XGBoostModel
¶
XGBoost模型封装类。
提供统一的XGBoost模型训练、预测、保存和加载接口。 支持模型校准、特征重要性获取等功能。
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
params
|
dict
|
XGBoost模型参数字典 |
必需 |
model
|
XGBClassifier
|
预加载的模型实例 |
None
|
示例:
>>> xgb_clf = XGBoostModel(params)
>>> xgb_clf.fit(x_train, y_train, x_val, y_val)
>>> preds = xgb_clf.predict(x_test)
源代码位于: Modeling_Tool/Model/GBM_Tool.py
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 | |
fit
¶
训练XGBoost模型。
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
x
|
array - like or DataFrame
|
训练集特征 |
必需 |
y
|
array - like
|
训练集标签 |
必需 |
valx
|
array - like or DataFrame
|
验证集特征 |
必需 |
valy
|
array - like
|
验证集标签 |
必需 |
sample_weight
|
array - like
|
样本权重 |
None
|
sample_weight_eval_set
|
list
|
验证集样本权重列表 |
None
|
base_margin
|
array - like
|
基础边际(init_score / log-odds 偏移),用于增量训练(warm-start)。 |
None
|
返回:
| 类型 | 描述 |
|---|---|
self
|
|
源代码位于: Modeling_Tool/Model/GBM_Tool.py
predict
¶
预测样本的概率。
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
x
|
array - like or DataFrame
|
预测特征 |
必需 |
返回:
| 类型 | 描述 |
|---|---|
ndarray
|
预测概率 |
get_feature_importance
¶
获取特征重要性。
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
importance_type
|
str
|
特征重要性类型 |
'gain'
|
返回:
| 类型 | 描述 |
|---|---|
DataFrame
|
包含 feature 和 importance 列的DataFrame |
源代码位于: Modeling_Tool/Model/GBM_Tool.py
save
¶
load
¶
calibrate
¶
模型概率校准。
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
x
|
array - like
|
校准特征 |
必需 |
y
|
array - like
|
校准标签 |
必需 |
method
|
str
|
校准方法 |
'sigmoid'
|
cv
|
str or int
|
交叉验证方式 |
'prefit'
|
返回:
| 类型 | 描述 |
|---|---|
self
|
|
源代码位于: Modeling_Tool/Model/GBM_Tool.py
calibration_curve
¶
获取校准曲线数据。
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
x
|
array - like
|
特征 |
必需 |
y
|
array - like
|
标签 |
必需 |
返回:
| 类型 | 描述 |
|---|---|
tuple
|
|
源代码位于: Modeling_Tool/Model/GBM_Tool.py
brier_score
¶
计算Brier分数。
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
x
|
array - like
|
|
必需 |
y
|
array - like
|
|
必需 |
返回:
| 类型 | 描述 |
|---|---|
float
|
|
roc_auc
¶
计算ROC AUC。
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
x
|
array - like
|
|
必需 |
y
|
array - like
|
|
必需 |
返回:
| 类型 | 描述 |
|---|---|
float
|
|
CatBoostModel
¶
CatBoost模型封装类。
提供统一的CatBoost模型训练、预测、保存和加载接口。 支持模型校准、特征重要性获取等功能。
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
params
|
dict
|
CatBoost模型参数字典 |
必需 |
model
|
CatBoostClassifier
|
预加载的模型实例 |
None
|
示例:
>>> cat_clf = CatBoostModel(params)
>>> cat_clf.fit(x_train, y_train, x_val, y_val)
>>> preds = cat_clf.predict(x_test)
源代码位于: Modeling_Tool/Model/GBM_Tool.py
1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 | |
fit
¶
训练CatBoost模型。
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
x
|
array - like or DataFrame
|
训练集特征 |
必需 |
y
|
array - like
|
训练集标签 |
必需 |
valx
|
array - like or DataFrame
|
验证集特征 |
必需 |
valy
|
array - like
|
验证集标签 |
必需 |
sample_weight
|
array - like
|
样本权重 |
None
|
返回:
| 类型 | 描述 |
|---|---|
self
|
|
源代码位于: Modeling_Tool/Model/GBM_Tool.py
predict
¶
预测样本的概率。
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
x
|
array - like or DataFrame
|
预测特征 |
必需 |
返回:
| 类型 | 描述 |
|---|---|
ndarray
|
预测概率 |
get_feature_importance
¶
获取特征重要性。
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
importance_type
|
str
|
特征重要性类型(CatBoost 使用 PredictionValuesChange) |
'gain'
|
返回:
| 类型 | 描述 |
|---|---|
DataFrame
|
包含 feature 和 importance 列的DataFrame |
源代码位于: Modeling_Tool/Model/GBM_Tool.py
save
¶
load
¶
加载模型。
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
path
|
str
|
模型文件路径 |
必需 |
返回:
| 类型 | 描述 |
|---|---|
self
|
|
calibrate
¶
模型概率校准。
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
x
|
array - like
|
校准特征 |
必需 |
y
|
array - like
|
校准标签 |
必需 |
method
|
str
|
校准方法 |
'sigmoid'
|
cv
|
str or int
|
交叉验证方式 |
'prefit'
|
返回:
| 类型 | 描述 |
|---|---|
self
|
|
源代码位于: Modeling_Tool/Model/GBM_Tool.py
calibration_curve
¶
获取校准曲线数据。
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
x
|
array - like
|
特征 |
必需 |
y
|
array - like
|
标签 |
必需 |
n_bins
|
int
|
分箱数 |
10
|
返回:
| 类型 | 描述 |
|---|---|
tuple
|
|
源代码位于: Modeling_Tool/Model/GBM_Tool.py
brier_score
¶
计算Brier分数。
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
x
|
array - like
|
|
必需 |
y
|
array - like
|
|
必需 |
返回:
| 类型 | 描述 |
|---|---|
float
|
|
roc_auc
¶
计算ROC AUC。
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
x
|
array - like
|
|
必需 |
y
|
array - like
|
|
必需 |
返回:
| 类型 | 描述 |
|---|---|
float
|
|
GradientBoostingModel
¶
统一梯度提升模型封装类。
支持LightGBM、XGBoost和CatBoost三种框架的统一接口。 通过model_type参数切换框架,其他接口保持一致。
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
model_type
|
str
|
模型类型,'lgb'、'xgb' 或 'cat'('catboost' 别名) |
必需 |
params
|
dict
|
模型参数字典 |
必需 |
示例:
>>> model = GradientBoostingModel('lgb', params)
>>> model.fit(x_train, y_train, x_val, y_val)
>>> preds = model.predict(x_test)
增量学习(warm-start)¶
>>> base_margin = init_model.get_base_margin(x_train)
>>> new_model = GradientBoostingModel('xgb', params)
>>> new_model.fit(x_train, y_train, x_val, y_val, init_score=base_margin)
>>> proba = new_model.predict_with_base_margin(
... x_score, init_model.get_base_margin(x_score))
适配已训练好的裸估计器(如历史直接 pickle 的 XGBClassifier)¶
>>> init_model = GradientBoostingModel.from_fitted(load_model(path))
>>> init_model.get_base_margin(x_train)
源代码位于: Modeling_Tool/Model/GBM_Tool.py
1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 | |
from_fitted
classmethod
¶
用一个【已训练好】的估计器(或封装)构造 GradientBoostingModel。
用于适配历史上直接以 sklearn 估计器(XGBClassifier /
LGBMClassifier / CatBoostClassifier)形式保存的模型,使其无需重训即可使用
:meth:get_base_margin / :meth:predict_with_base_margin 等统一接口。
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
model
|
object
|
已 fit 的 |
必需 |
model_type
|
(lgb, xgb, cat)
|
不传则按估计器类型自动推断。 |
'lgb'
|
params
|
dict
|
参数字典;不传则尽量从估计器的 |
None
|
返回:
| 类型 | 描述 |
|---|---|
GradientBoostingModel
|
|
引发:
| 类型 | 描述 |
|---|---|
ValueError
|
传入未 fit / 空模型时。 |
源代码位于: Modeling_Tool/Model/GBM_Tool.py
fit
¶
fit(x, y, valx, valy, init_score=None, sample_weight=None, eval_sample_weight=None, sample_weight_eval_set=None, **kwargs)
训练模型(支持增量学习 warm-start)。
当传入 init_score 时,以其作为 log-odds 偏移在新数据上继续训练:
LightGBM 走 init_score,XGBoost 走 base_margin(两者语义一致,
本方法统一对外暴露为 init_score)。CatBoost 不支持 init_score。
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
x
|
array - like or DataFrame
|
训练集特征 |
必需 |
y
|
array - like
|
训练集标签 |
必需 |
valx
|
array - like or DataFrame
|
验证集特征 |
必需 |
valy
|
array - like
|
验证集标签 |
必需 |
init_score
|
array - like
|
初始 log-odds 偏移(增量学习起点)。一般由基准模型的
:meth: |
None
|
**kwargs
|
其余参数透传给底层模型(如 lgb 的 |
{}
|
返回:
| 类型 | 描述 |
|---|---|
self
|
|
引发:
| 类型 | 描述 |
|---|---|
NotImplementedError
|
CatBoost 不支持 |
Notes
与既有生产流程一致,偏移仅作用于训练集;验证集未注入偏移,因此早停
的 eval 指标是在"未加偏移"的空间上评估的。如需严格一致,可后续透传
lgb 的 eval_init_score / xgb 的 base_margin_eval_set。
源代码位于: Modeling_Tool/Model/GBM_Tool.py
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 | |
get_base_margin
¶
返回本模型对 x 的原始 log-odds(base margin / init score)。
统一兼容三种框架取"未经 sigmoid 的原始分数":
- XGBoost:
predict(x, output_margin=True) - LightGBM:
predict(x, raw_score=True) - CatBoost:
predict(x, prediction_type='RawFormulaVal')
该结果可作为下一个增量模型 :meth:fit 的 init_score,或喂给
:meth:predict_with_base_margin 做融合预测。
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
x
|
array - like or DataFrame
|
待计算的特征 |
必需 |
返回:
| 类型 | 描述 |
|---|---|
ndarray
|
一维 log-odds 数组,形状 |
引发:
| 类型 | 描述 |
|---|---|
RuntimeError
|
当模型尚未训练( |
源代码位于: Modeling_Tool/Model/GBM_Tool.py
predict_with_base_margin
¶
融合预测:sigmoid(base_margin + 本模型 raw score)。
把一个基准模型的 log-odds(base_margin,通常来自
init_model.get_base_margin(x))与本(增量)模型自身的 raw score
在 log-odds 空间相加,再做 sigmoid。这种手动融合是唯一对 lgb 与 xgb
行为一致的方式——LightGBM 在预测期并不支持注入 init_score。
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
x
|
array - like or DataFrame
|
待预测的特征 |
必需 |
base_margin
|
array - like
|
基准模型的 log-odds 偏移,形状须与 |
必需 |
return_prob
|
bool
|
|
True
|
返回:
| 类型 | 描述 |
|---|---|
ndarray
|
一维数组, |
源代码位于: Modeling_Tool/Model/GBM_Tool.py
predict
¶
预测样本的概率。
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
x
|
array - like or DataFrame
|
|
必需 |
返回:
| 类型 | 描述 |
|---|---|
ndarray
|
|
get_feature_importance
¶
save
¶
load
¶
calibrate
¶
brier_score
¶
set_num_leaves
¶
根据最大深度设置叶子节点数,避免过拟合。
根据给定的最大深度和权重系数,计算合适的叶子节点数量。 计算公式:2^max_depth - 2^max_depth * wgt
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
max_depth
|
int
|
树的最大深度 |
5
|
wgt
|
float
|
权重系数,取値范围[0, 1] |
1
|
返回:
| 类型 | 描述 |
|---|---|
int
|
建议的叶子节点数 |
示例:
源代码位于: Modeling_Tool/Model/GBM_Tool.py
lgb_model
¶
快速训练LightGBM模型。
使用训练集和验证集训练LightGBM模型,支持早停机制。
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
x
|
array - like or DataFrame
|
训练集特征 |
必需 |
y
|
array - like
|
训练集标签 |
必需 |
valx
|
array - like or DataFrame
|
验证集特征 |
必需 |
valy
|
array - like
|
验证集标签 |
必需 |
params_dict
|
dict
|
LightGBM参数字典 |
必需 |
wgt
|
array - like
|
样本权重 |
None
|
init_score
|
array - like
|
初始化分数 |
None
|
返回:
| 类型 | 描述 |
|---|---|
LGBMClassifier
|
训练好的LightGBM模型 |
示例:
>>> params = {
... 'n_estimators': 100,
... 'max_depth': 5,
... 'learning_rate': 0.1,
... 'early_stopping_rounds': 20,
... 'eval_metric': 'auc'
... }
>>> model = lgb_model(x_train, y_train, x_val, y_val, params)
源代码位于: Modeling_Tool/Model/GBM_Tool.py
lgb_varimp
¶
获取LightGBM模型特征重要性。
返回按特征重要性排序的DataFrame。
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
model
|
LGBMClassifier
|
训练好的LightGBM模型 |
必需 |
返回:
| 类型 | 描述 |
|---|---|
DataFrame
|
包含 feature 和 importance 列的DataFrame,按重要性降序排列 |
示例:
源代码位于: Modeling_Tool/Model/GBM_Tool.py
lgbm_quick_train
¶
lgbm_quick_train(train_data, validation_data, x, y, params, wgt_col=None, val_wgt_col=None, cat_x_train=None)
快速训练LightGBM模型(使用DataFrame接口)。
接受DataFrame格式的训练集和验证集,自动提取特征和标签。
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
train_data
|
DataFrame
|
训练数据集 |
必需 |
validation_data
|
DataFrame
|
验证数据集 |
必需 |
x
|
list of str
|
特征列名列表 |
必需 |
y
|
str
|
目标变量列名 |
必需 |
params
|
dict
|
LightGBM参数字典 |
必需 |
wgt_col
|
str
|
样本权重列名 |
None
|
cat_x_train
|
list of str
|
类别型特征列名列表 |
None
|
返回:
| 类型 | 描述 |
|---|---|
LGBMClassifier
|
训练好的LightGBM模型 |
示例:
>>> model = lgbm_quick_train(
... train_data=train_df,
... validation_data=val_df,
... x=['feat1', 'feat2'],
... y='target',
... params=params_dict
... )
源代码位于: Modeling_Tool/Model/GBM_Tool.py
xgb_model
¶
xgb_model(x, y, valx, valy, params_dict, sample_weight=None, sample_weight_eval_set=None, base_margin=None)
训练XGBoost模型。
使用训练集和验证集训练XGBoost模型,支持早停机制。
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
x
|
array - like or DataFrame
|
训练集特征 |
必需 |
y
|
array - like
|
训练集标签 |
必需 |
valx
|
array - like or DataFrame
|
验证集特征 |
必需 |
valy
|
array - like
|
验证集标签 |
必需 |
params_dict
|
dict
|
XGBoost参数字典 |
必需 |
sample_weight
|
array - like
|
训练集样本权重 |
None
|
sample_weight_eval_set
|
list
|
验证集样本权重列表 |
None
|
base_margin
|
array - like
|
基础边际度 |
None
|
返回:
| 类型 | 描述 |
|---|---|
XGBClassifier
|
训练好的XGBoost模型 |
示例:
>>> params = {
... 'n_estimators': 100,
... 'max_depth': 5,
... 'learning_rate': 0.1,
... 'early_stopping_rounds': 20,
... 'eval_metric': 'auc'
... }
>>> model = xgb_model(x_train, y_train, x_val, y_val, params)
源代码位于: Modeling_Tool/Model/GBM_Tool.py
xgb_varimp
¶
获取XGBoost模型特征重要性。
返回按特征重要性排序的DataFrame。
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
model
|
XGBClassifier
|
训练好的XGBoost模型 |
必需 |
返回:
| 类型 | 描述 |
|---|---|
DataFrame
|
包含 feature 和 importance 列的DataFrame,按重要性降序排列 |
示例:
源代码位于: Modeling_Tool/Model/GBM_Tool.py
xgbm_quick_train
¶
xgbm_quick_train(train_data, validation_data, x, y, wgt_col=None, params=None, sample_weight_eval_set=None, val_wgt_col=None)
快速训练XGBoost模型(使用DataFrame接口)。
接受DataFrame格式的训练集和验证集,自动提取特征和标签。
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
train_data
|
DataFrame
|
训练数据集 |
必需 |
validation_data
|
DataFrame
|
验证数据集 |
必需 |
x
|
list of str
|
特征列名列表 |
必需 |
y
|
str
|
目标变量列名 |
必需 |
wgt_col
|
str
|
样本权重列名 |
None
|
params
|
dict
|
XGBoost参数字典 |
None
|
sample_weight_eval_set
|
list
|
验证集样本权重列表 |
None
|
返回:
| 类型 | 描述 |
|---|---|
XGBClassifier
|
训练好的XGBoost模型 |
示例:
>>> model = xgbm_quick_train(
... train_data=train_df,
... validation_data=val_df,
... x=['feat1', 'feat2'],
... y='target',
... wgt_col='weight',
... params=params_dict
... )
源代码位于: Modeling_Tool/Model/GBM_Tool.py
catboost_model
¶
训练CatBoost模型。
使用训练集和验证集训练CatBoost模型,支持早停机制。
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
x
|
array - like or DataFrame
|
训练集特征 |
必需 |
y
|
array - like
|
训练集标签 |
必需 |
valx
|
array - like or DataFrame
|
验证集特征 |
必需 |
valy
|
array - like
|
验证集标签 |
必需 |
params_dict
|
dict
|
CatBoost参数字典(支持 n_estimators / max_depth / random_state 别名) |
必需 |
sample_weight
|
array - like
|
训练集样本权重 |
None
|
返回:
| 类型 | 描述 |
|---|---|
CatBoostClassifier
|
训练好的CatBoost模型 |
示例:
>>> params = {
... 'n_estimators': 100,
... 'max_depth': 5,
... 'learning_rate': 0.1,
... 'early_stopping_rounds': 20,
... 'eval_metric': 'AUC'
... }
>>> model = catboost_model(x_train, y_train, x_val, y_val, params)
源代码位于: Modeling_Tool/Model/GBM_Tool.py
catboost_varimp
¶
获取CatBoost模型特征重要性。
返回按特征重要性排序的DataFrame。
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
model
|
CatBoostClassifier
|
训练好的CatBoost模型 |
必需 |
返回:
| 类型 | 描述 |
|---|---|
DataFrame
|
包含 feature 和 importance 列的DataFrame,按重要性降序排列 |
示例:
源代码位于: Modeling_Tool/Model/GBM_Tool.py
catboost_quick_train
¶
catboost_quick_train(train_data, validation_data, x, y, params, wgt_col=None, val_wgt_col=None, cat_features=None)
快速训练CatBoost模型(使用DataFrame接口)。
接受DataFrame格式的训练集和验证集,自动提取特征和标签。
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
train_data
|
DataFrame
|
训练数据集 |
必需 |
validation_data
|
DataFrame
|
验证数据集 |
必需 |
x
|
list of str
|
特征列名列表 |
必需 |
y
|
str
|
目标变量列名 |
必需 |
params
|
dict
|
CatBoost参数字典 |
必需 |
wgt_col
|
str
|
样本权重列名 |
None
|
cat_features
|
list
|
类别型特征列名或索引列表 |
None
|
返回:
| 类型 | 描述 |
|---|---|
CatBoostClassifier
|
训练好的CatBoost模型 |
示例:
>>> model = catboost_quick_train(
... train_data=train_df,
... validation_data=val_df,
... x=['feat1', 'feat2'],
... y='target',
... params=params_dict
... )
源代码位于: Modeling_Tool/Model/GBM_Tool.py
后向变量消元 — Backward_Tool¶
Backward_Tool
¶
向后变量消除工具包(统一版)¶
本模块提供基于LightGBM和XGBoost的向后变量消除(Backward Variable Elimination)功能, 通过累计特征重要性阈值进行变量筛选,并支持训练后的性能分析。
函数:
| 名称 | 描述 |
|---|---|
backward_lgbm |
使用LightGBM模型进行向后变量消除 |
backward_xgbm |
使用XGBoost模型进行向后变量消除 |
类:
| 名称 | 描述 |
|---|---|
BackwardVariableEliminator |
向后变量消除器,支持LightGBM和XGBoost |
BackwardEliminationAnalyzer |
向后消除结果分析器 |
BackwardVariableEliminator
¶
向后变量消除器。
封装LightGBM/XGBoost向后变量消除流程, 支持多轮消除和结果汇总。
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
train_data
|
DataFrame
|
训练数据集 |
必需 |
varlist
|
list of str
|
初始特征变量列表 |
必需 |
dep
|
str
|
目标变量列名 |
必需 |
model_type
|
str
|
模型类型,可选 "lgbm" 或 "xgbm" |
"lgbm"
|
validation_data
|
DataFrame
|
验证数据集 |
None
|
test_data_dict
|
dict
|
测试数据集字典 |
None
|
示例:
>>> eliminator = BackwardVariableEliminator(
... train_data=train_df,
... varlist=feature_cols,
... dep='target',
... model_type='lgbm',
... validation_data=val_df
... )
>>> results = eliminator.run(n_rounds=5)
源代码位于: Modeling_Tool/Model/Backward_Tool.py
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 | |
run
¶
run(n_rounds: int = 5, varreduct_params: Optional[Dict] = None, stopping_metric: str = 'auc', seed: int = 42, num_boost_round: int = 200, early_stopping_rounds: int = 20, importance_type: str = 'gain', cum_importance_threshold: float = 0.99, min_vars: int = 10, ret_perf: bool = True, nbins: int = 10, **kwargs) -> List[Dict]
运行多轮向后变量消除。
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
n_rounds
|
int
|
消除轮数 |
5
|
varreduct_params
|
dict
|
模型超参数 |
None
|
stopping_metric
|
str
|
早停指标 |
"auc"
|
seed
|
int
|
随机种子 |
42
|
num_boost_round
|
int
|
最大迭代轮数 |
200
|
early_stopping_rounds
|
int
|
早停轮数 |
20
|
importance_type
|
str
|
特征重要性类型 |
"gain"
|
cum_importance_threshold
|
float
|
累计重要性阈值 |
0.99
|
min_vars
|
int
|
最小保留变量数 |
10
|
ret_perf
|
bool
|
是否返回性能指标 |
True
|
nbins
|
int
|
分箱数 |
10
|
返回:
| 类型 | 描述 |
|---|---|
list of dict
|
每轮消除结果列表 |
源代码位于: Modeling_Tool/Model/Backward_Tool.py
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 | |
get_final_vars
¶
get_summary
¶
获取每轮消除汇总表。
源代码位于: Modeling_Tool/Model/Backward_Tool.py
BackwardEliminationAnalyzer
¶
向后消除结果分析器。
对 BackwardVariableEliminator 的运行结果进行分析和可视化。
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
results
|
list of dict
|
BackwardVariableEliminator.run() 的返回值 |
必需 |
示例:
>>> analyzer = BackwardEliminationAnalyzer(results)
>>> analyzer.plot_var_reduction()
>>> final_vars = analyzer.get_stable_vars(top_n=20)
源代码位于: Modeling_Tool/Model/Backward_Tool.py
725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 | |
get_stable_vars
¶
获取在所有轮次中均被保留的稳定变量。
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
top_n
|
int
|
返回前N个稳定变量,None表示返回全部 |
None
|
返回:
| 类型 | 描述 |
|---|---|
list of str
|
|
源代码位于: Modeling_Tool/Model/Backward_Tool.py
plot_var_reduction
¶
绘制变量数量随消除轮次变化的折线图。
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
figsize
|
tuple
|
图形尺寸 |
(8, 4)
|
save_path
|
str
|
图片保存路径,None表示直接显示 |
None
|
源代码位于: Modeling_Tool/Model/Backward_Tool.py
get_perf_trend
¶
获取指定数据集上性能指标随轮次变化趋势。
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
dataset
|
str
|
数据集名称,如 "mdl", "hd", "oot" |
"mdl"
|
metric
|
str
|
性能指标列名 |
"IV"
|
返回:
| 类型 | 描述 |
|---|---|
DataFrame
|
|
源代码位于: Modeling_Tool/Model/Backward_Tool.py
backward_lgbm
¶
backward_lgbm(train_data, varlist: List[str], dep: str, varreduct_params=None, stopping_metric='auc', seed=42, num_boost_round: int = 200, early_stopping_rounds: int = 20, importance_type: str = 'gain', cum_importance_threshold: float = 0.99, min_vars: int = 10, validation_data=None, test_data_dict=None, ret_perf: bool = True, nbins: int = 10, precision: int = 5, min_bin_prop: float = 0.05, include_missing: bool = True, equal_freq: bool = True, ascending: bool = True, fillna: Optional[float] = None, spec_values: Optional[List] = None, weight_col: Optional[str] = None, validation_weight_col: Optional[str] = None, wgt_col=None)
使用LightGBM模型进行向后变量消除。
通过训练LightGBM模型并根据特征重要性累计阈值筛选变量, 实现向后变量消除(Backward Variable Elimination)。
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
train_data
|
DataFrame
|
训练数据集,必须包含dep列和varlist中的所有特征列 |
必需 |
varlist
|
list of str
|
参与建模的特征变量列表 |
必需 |
dep
|
str
|
目标变量列名(0/1二元变量) |
必需 |
varreduct_params
|
dict
|
LightGBM超参数字典,未指定的必需参数将使用预设值 |
None
|
stopping_metric
|
str
|
早停评估指标,可选 "auc", "binary_logloss" 等 |
"auc"
|
seed
|
int
|
随机种子,保证可复现性 |
42
|
num_boost_round
|
int
|
最大迭代轮数 |
200
|
early_stopping_rounds
|
int
|
早停轮数,验证集指标连续N轮无提升则停止 |
20
|
importance_type
|
str
|
特征重要性类型,可选 "gain", "split" |
"gain"
|
cum_importance_threshold
|
float
|
累计特征重要性阈值,筛选覆盖该比例重要性的最少特征 |
0.99
|
min_vars
|
int
|
保留的最小变量数量 |
10
|
validation_data
|
DataFrame
|
验证数据集,用于早停 |
None
|
test_data_dict
|
dict
|
测试数据集字典,格式为 {名称: DataFrame} |
None
|
ret_perf
|
bool
|
是否返回模型性能指标 |
True
|
nbins
|
int
|
增益表分箱数 |
10
|
precision
|
int
|
数值精度 |
5
|
min_bin_prop
|
float
|
最小分箱比例 |
0.05
|
include_missing
|
bool
|
是否包含缺失值分箱 |
True
|
equal_freq
|
bool
|
是否使用等频分箱 |
True
|
ascending
|
bool
|
增益表是否升序排列 |
True
|
fillna
|
float
|
缺失值填充值 |
None
|
spec_values
|
list
|
特殊值列表 |
None
|
返回:
| 类型 | 描述 |
|---|---|
tuple
|
(selected_vars, model, perf_dict) 或 (selected_vars, model) |
引发:
| 类型 | 描述 |
|---|---|
TypeError
|
当输入数据不是pandas.DataFrame格式时 |
ImportError
|
当lightgbm未安装时 |
示例:
>>> selected_vars, model, perf = backward_lgbm(
... train_data=train_df,
... varlist=feature_cols,
... dep='target',
... validation_data=val_df
... )
源代码位于: Modeling_Tool/Model/Backward_Tool.py
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 | |
backward_xgbm
¶
backward_xgbm(train_data, varlist: List[str], dep: str, varreduct_params=None, stopping_metric='auc', seed=42, num_boost_round: int = 200, early_stopping_rounds: int = 20, importance_type: str = 'gain', cum_importance_threshold: float = 0.99, min_vars: int = 10, validation_data=None, test_data_dict=None, ret_perf: bool = True, nbins: int = 10, precision: int = 5, min_bin_prop: float = 0.05, include_missing: bool = True, equal_freq: bool = True, ascending: bool = True, fillna: Optional[float] = None, spec_values: Optional[List] = None, monotone_constraints: Optional[Dict[str, int]] = None, weight_col: Optional[str] = None, validation_weight_col: Optional[str] = None, wgt_col=None)
使用XGBoost模型进行向后变量消除。
通过训练XGBoost模型并根据特征重要性累计阈值筛选变量, 实现向后变量消除(Backward Variable Elimination)。
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
train_data
|
DataFrame
|
训练数据集,必须包含dep列和varlist中的所有特征列 |
必需 |
varlist
|
list of str
|
参与建模的特征变量列表 |
必需 |
dep
|
str
|
目标变量列名(0/1二元变量) |
必需 |
varreduct_params
|
dict
|
XGBoost超参数字典,未指定的必需参数将使用预设值 |
None
|
stopping_metric
|
str
|
早停评估指标 |
"auc"
|
seed
|
int
|
随机种子 |
42
|
num_boost_round
|
int
|
最大迭代轮数 |
200
|
early_stopping_rounds
|
int
|
早停轮数 |
20
|
importance_type
|
str
|
特征重要性类型 |
"gain"
|
cum_importance_threshold
|
float
|
累计特征重要性阈值 |
0.99
|
min_vars
|
int
|
保留的最小变量数量 |
10
|
validation_data
|
DataFrame
|
验证数据集 |
None
|
test_data_dict
|
dict
|
测试数据集字典 |
None
|
ret_perf
|
bool
|
是否返回性能指标 |
True
|
nbins
|
int
|
增益表分箱数 |
10
|
precision
|
int
|
数值精度 |
5
|
min_bin_prop
|
float
|
最小分箱比例 |
0.05
|
include_missing
|
bool
|
是否包含缺失值分箱 |
True
|
equal_freq
|
bool
|
是否使用等频分箱 |
True
|
ascending
|
bool
|
增益表是否升序排列 |
True
|
fillna
|
float
|
缺失值填充值 |
None
|
spec_values
|
list
|
特殊值列表 |
None
|
monotone_constraints
|
dict
|
单调约束字典,格式为 {特征名: 1/-1} |
None
|
返回:
| 类型 | 描述 |
|---|---|
tuple
|
(selected_vars, model, perf_dict) 或 (selected_vars, model) |
引发:
| 类型 | 描述 |
|---|---|
TypeError
|
当输入数据不是pandas.DataFrame格式时 |
ImportError
|
当xgboost未安装时 |
示例:
>>> selected_vars, model, perf = backward_xgbm(
... train_data=train_df,
... varlist=feature_cols,
... dep='target',
... validation_data=val_df
... )
源代码位于: Modeling_Tool/Model/Backward_Tool.py
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 | |