Modeling_Tool.Eval¶
Model evaluation layer: Gains tables, KS/AUC summaries, challenger-versus-champion comparison, slice-by-slice evaluation,
and ROC/KDE/percentile/gain figures. Passing weight_col or sample_weight takes the weighted path; omitting them keeps the
historical unweighted behavior.
User guide: Model Evaluation, including Sample-Weighted Evaluation.
Gains Tables and Performance Summaries: Model_Eval_Tool¶
Model_Eval_Tool
¶
GainsTableCalculator
¶
Gains table calculator.
Integrates the various Gains table functions and supports both the basic Gains table and the Gains table with custom metrics. Provides an object-oriented interface for computing grouped Gains tables.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame
|
Input data table. |
required |
dep
|
str
|
Name of the target variable. |
required |
nbins
|
int
|
Number of bins. |
10
|
precision
|
int
|
Precision of the bin boundary values. |
5
|
min_bin_prop
|
float
|
Minimum proportion of samples per bin. |
0.05
|
include_missing
|
bool
|
Whether missing scores are binned. True fills them with |
True
|
score
|
str
|
Name of the score column. |
None
|
model
|
sklearn-like model
|
Machine learning model. |
None
|
varlist
|
list
|
List of model features. |
None
|
equal_freq
|
bool
|
True for equal-frequency binning. |
True
|
chi2_method
|
bool
|
Whether to use chi-square binning. |
False
|
chi2_p
|
float
|
Significance level of the chi-square test. |
0.95
|
init_equi_bins
|
int
|
Initial number of equal-frequency bins. |
100
|
fillna
|
any
|
Fill value for missing values. |
-999999
|
spec_values
|
list
|
List of special values. |
[]
|
tree_binning
|
bool
|
Whether to use decision-tree binning. |
False
|
random_state
|
int
|
Random seed. |
42
|
ascending
|
bool
|
Whether the bin order is ascending. |
False
|
weight_col
|
str
|
Name of the sample weight column (must be in |
None
|
weighted_binning
|
bool
|
Accepted for compatibility but without any effect: the weighted Gains table always uses equal-frequency bins by cumulative weight. |
None
|
Examples:
>>> calc = GainsTableCalculator(data, dep='target', score='score', nbins=10)
>>> result = calc.calculate(grp_name='region')
Source code in Modeling_Tool/Eval/Model_Eval_Tool.py
2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 | |
calculate
¶
calculate(grp_name=None, min_data_size=100, grp_colname=None, sync_range=True, retSummary=False, withSummary=False, wholeGroup=False, add_func=None, weight_col=None)
Compute the Gains table.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
grp_name
|
str
|
Name of the grouping column. |
None
|
min_data_size
|
int
|
Minimum number of samples per group. |
100
|
grp_colname
|
str
|
Name of the group column in the output. |
None
|
sync_range
|
bool
|
Whether to synchronize the bin boundaries across groups. |
True
|
retSummary
|
bool
|
Whether to return only the summary metrics. |
False
|
withSummary
|
bool
|
Whether to include an overall summary row. |
False
|
wholeGroup
|
bool
|
Whether to use all the data for binning. |
False
|
add_func
|
callable
|
Custom statistics function. It receives the rows of one bin as a DataFrame (all the columns of |
None
|
weight_col
|
str
|
Sample weight column for this call; it overrides the |
None
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
Gains table. |
Notes
The call is delegated to get_gains_table with the settings of the calculator. When a weight column applies and
grp_name is None, the weighted Gains table (bins 1 to nbins, each with about 1 / nbins of the total
weight) is returned, with the add_func columns and the Grand Summary row when they are asked for; with
grp_name the weights are ignored.
Like get_gains_table, it returns the integer -1, -2 or -3 (instead of raising) when neither score nor a
model with varlist was given to the calculator.
Source code in Modeling_Tool/Eval/Model_Eval_Tool.py
2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 | |
PerformanceEvaluator
¶
Performance evaluator.
Integrates the various model performance evaluation functions and supports evaluation across multiple datasets and multiple groups. Provides an object-oriented interface for computing and summarizing performance metrics.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tgt_name
|
str or list of str
|
Name of the target variable. A list/tuple of several y labels can be passed: each label is evaluated
separately and the results are stacked vertically (the output gains a |
required |
scr_name
|
str
|
Name of the score column. |
None
|
model
|
sklearn-like model
|
Machine learning model. |
None
|
feature_cols
|
list
|
List of model features. |
None
|
dist_bins
|
int
|
Number of bins for the score distribution. |
20
|
pct_bins
|
int
|
Number of percentile bins. |
10
|
precision
|
int
|
Precision of the bin boundary values. |
5
|
min_bin_prop
|
float
|
Minimum share of a bin in the Gains tables of |
0.05
|
include_missing
|
bool
|
Whether to include missing values. |
False
|
equal_freq
|
bool
|
True for equal-frequency binning. |
True
|
chi2_method
|
bool
|
Whether to use chi-square binning. |
False
|
init_equi_bins
|
int
|
Initial number of equal-frequency bins. |
1000
|
chi2_p
|
float
|
Significance level of the chi-square test. |
0.9
|
tree_binning
|
bool
|
Whether to use decision-tree binning. |
False
|
random_state
|
int
|
Random seed. |
42
|
weight_col
|
str
|
Default weight column; each |
None
|
spec_values
|
list
|
Sentinel score values (for example -1 for a score override) that carry no ordering information. Rows with such a
score are left out of the ranking metrics ( |
None
|
ascending
|
bool
|
Score direction applied uniformly to the summary, the Gains tables and the figures, including the weighted paths. Default is None, which keeps the legacy direction of every underlying function. |
None
|
Attributes:
| Name | Type | Description |
|---|---|---|
datasets |
dict
|
The datasets added with |
dataset_weight_cols |
dict
|
The weight column given to |
evaluate_status |
str or None
|
Outcome of the last |
Examples:
>>> evaluator = PerformanceEvaluator(tgt_name='target', model=model, feature_cols=features)
>>> evaluator.add_dataset('train', train_df)
>>> evaluator.add_dataset('validation', val_df)
>>> evaluator.add_dataset('oot', oot_df)
>>> result = evaluator.evaluate()
>>>
>>> # Multiple y labels: pass a list as tgt_name -> a vertically stacked table with a tgt_name column, one figure per label
>>> evaluator = PerformanceEvaluator(tgt_name=['bad_dpd7', 'bad_dpd30'], model=model, feature_cols=features)
>>> evaluator.add_dataset('train', train_df).add_dataset('oot', oot_df)
>>> result = evaluator.evaluate(to_show=True)
Source code in Modeling_Tool/Eval/Model_Eval_Tool.py
2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 | |
add_dataset
¶
Add a dataset.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Name of the dataset (e.g. 'train', 'validation', 'oot'). |
required |
data
|
DataFrame
|
Dataset. |
required |
weight_col
|
str
|
Sample weight column of this dataset (must be in |
None
|
overwrite
|
bool
|
Whether a dataset that already has this |
False
|
Returns:
| Type | Description |
|---|---|
self
|
The evaluator itself, to allow method chaining. |
Raises:
| Type | Description |
|---|---|
KeyError
|
If a dataset named |
Source code in Modeling_Tool/Eval/Model_Eval_Tool.py
evaluate
¶
evaluate(oot_grp_name=None, min_data_size=100, grp_colname=None, fig_save_path=None, rpt_save_path=None, to_show=False, display=True, gains_table=False, benchmark_dataset=None, weight_col=None)
Run the performance evaluation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
oot_grp_name
|
str
|
Name of the grouping column. Every added dataset that has this column (not only the OOT data) is evaluated
separately for each group value, and the datasets without it are skipped. Weights and |
None
|
min_data_size
|
int
|
Minimum number of samples per group. |
100
|
grp_colname
|
str
|
Name of the group column in the output. Default is None, i.e. |
None
|
fig_save_path
|
str
|
Path to save the figure. It is ignored when |
None
|
rpt_save_path
|
str
|
Path to save the report (a CSV file of the summary table). |
None
|
to_show
|
bool
|
Whether to display the figures. |
False
|
display
|
bool
|
Whether to show the result table with |
True
|
gains_table
|
bool
|
Whether the percentile panel and the Top/Btm target rates are built from the Gains-table binning (the
|
False
|
benchmark_dataset
|
str or DataFrame
|
Benchmark dataset used to fix the bin boundaries. If a str is passed, the dataset is looked up by name
among the datasets added with |
None
|
weight_col
|
str
|
Sample weight column for this call; it overrides the |
None
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
Performance evaluation summary table. If |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Notes
The attribute evaluate_status records the outcome of the call ('ok', 'no_datasets',
'compute_failed' or 'empty_input').
Source code in Modeling_Tool/Eval/Model_Eval_Tool.py
2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 | |
get_gains_table
¶
get_gains_table(data, dep, nbins=10, precision=5, min_bin_prop=0.05, include_missing=True, score=None, model=None, varlist=None, equal_freq=True, chi2_method=False, grp_name=None, min_data_size=100, grp_colname=None, sync_range=True, chi2_p=0.95, init_equi_bins=100, fillna=-999999, spec_values=[], retSummary=False, tree_binning=False, random_state=42, ascending=False, withSummary=False, wholeGroup=False, add_func=None, weight_col=None, weighted_binning=None)
Compute the grouped Gains table.
Split the data into groups by the grouping column and compute the Gains table of each group separately. If no grouping column is specified, compute the overall Gains table.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame
|
Input data table. |
required |
dep
|
str
|
Name of the target variable. |
required |
nbins
|
int or list
|
Number of bins, or an explicit list of bin edges. |
10
|
precision
|
int
|
Precision of the bin boundary values. |
5
|
min_bin_prop
|
float
|
Minimum proportion of samples per bin. |
0.05
|
include_missing
|
bool
|
Whether missing scores are binned. True fills them with |
True
|
score
|
str
|
Name of the score column. |
None
|
model
|
sklearn-like model
|
Machine learning model. |
None
|
varlist
|
list
|
List of model features. |
None
|
equal_freq
|
bool
|
True for equal-frequency binning. |
True
|
chi2_method
|
bool
|
Whether to use chi-square binning. |
False
|
grp_name
|
str
|
Name of the grouping column. |
None
|
min_data_size
|
int
|
Minimum number of samples per group. |
100
|
grp_colname
|
str
|
Name of the group column in the output. |
None
|
sync_range
|
bool
|
Whether to synchronize the bin boundaries across groups. |
True
|
chi2_p
|
float
|
Significance level of the chi-square test. |
0.95
|
init_equi_bins
|
int
|
Initial number of equal-frequency bins. |
100
|
fillna
|
any
|
Fill value for missing values. |
-999999
|
spec_values
|
list
|
List of special values. |
[]
|
retSummary
|
bool
|
Whether to return only the summary metrics. |
False
|
tree_binning
|
bool
|
Whether to use decision-tree binning. |
False
|
random_state
|
int
|
Random seed. |
42
|
ascending
|
bool
|
Whether the bin order is ascending. |
False
|
withSummary
|
bool
|
Whether to include an overall summary row. |
False
|
wholeGroup
|
bool
|
Whether to use all the data for binning. |
False
|
add_func
|
callable
|
Custom statistics function. It receives the rows of one bin as a DataFrame (all the columns of |
None
|
weight_col
|
str
|
Name of the sample weight column; when provided and |
None
|
weighted_binning
|
bool
|
Accepted for compatibility but without any effect: the weighted Gains table always uses equal-frequency bins by cumulative weight, whatever its value. |
None
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
Grouped Gains table. With |
Notes
With weight_col and without grp_name the call is delegated to the weighted implementation, which only uses
nbins, the score (score, or model with varlist), ascending, include_missing, add_func,
withSummary and retSummary: precision, min_bin_prop, equal_freq, chi2_method, chi2_p,
init_equi_bins, fillna, spec_values, tree_binning and random_state are ignored. The weighted table has
the bins 1 to nbins, each holding about 1 / nbins of the total weight of the rows with a score; rows with a
missing score are left out, or reported in a Missing row with include_missing=True, and rows with a missing
target count in N but not in PERF_CNT or the bad and good counts. Its Grand Summary row
(withSummary=True) covers all the rows of the table (see weighted_eval_utils.get_gains_table). With
grp_name the weights are ignored and withSummary is forced to False.
Source code in Modeling_Tool/Eval/Model_Eval_Tool.py
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 | |
get_perf_summary
¶
get_perf_summary(train, validation, oot, tgt_name, scr_name=None, model=None, feature_cols=None, fig_save_path=None, rpt_save_path=None, to_show=False, display=True, dist_bins=20, pct_bins=10, precision=5, min_bin_prop=0.05, include_missing=False, equal_freq=True, chi2_method=False, init_equi_bins=1000, chi2_p=0.9, oot_grp_name=None, min_data_size=100, grp_colname=None, tree_binning=False, random_state=42, gains_table=False, weight_col=None)
Compute the grouped performance evaluation summary.
Evaluate the performance on the training, validation and OOT samples by group: the data are
split by the oot_grp_name column and the performance metrics of each group are computed separately.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
train
|
DataFrame
|
Training dataset. |
required |
validation
|
DataFrame
|
Validation dataset. |
required |
oot
|
DataFrame
|
Out-of-time (OOT) dataset. |
required |
tgt_name
|
str
|
Name of the target variable. |
required |
scr_name
|
str
|
Name of the score column. |
None
|
model
|
sklearn-like model
|
Machine learning model. |
None
|
feature_cols
|
list
|
List of model features. |
None
|
fig_save_path
|
str
|
Path to save the figure. |
None
|
rpt_save_path
|
str
|
Path to save the report. |
None
|
to_show
|
bool
|
Whether to display the figures. |
False
|
display
|
bool
|
Whether to print the results. |
True
|
dist_bins
|
int
|
Number of bins for the score distribution. |
20
|
pct_bins
|
int
|
Number of percentile bins. |
10
|
precision
|
int
|
Precision of the bin boundary values. |
5
|
min_bin_prop
|
float
|
Minimum proportion of samples per bin. |
0.05
|
include_missing
|
bool
|
Whether to include missing values. |
False
|
equal_freq
|
bool
|
True for equal-frequency binning. |
True
|
chi2_method
|
bool
|
Whether to use chi-square binning. |
False
|
init_equi_bins
|
int
|
Initial number of equal-frequency bins. |
1000
|
chi2_p
|
float
|
Significance level of the chi-square test. |
0.9
|
oot_grp_name
|
str
|
Name of the grouping column for the OOT data. |
None
|
min_data_size
|
int
|
Minimum number of samples per group. |
100
|
grp_colname
|
str
|
Name of the group column in the output. |
None
|
tree_binning
|
bool
|
Whether to use decision-tree binning. |
False
|
random_state
|
int
|
Random seed. |
42
|
gains_table
|
bool
|
Whether the percentile panel and the Top/Btm target rates are built from the Gains-table binning (the
|
False
|
weight_col
|
str
|
Sample weight column in each dataset DataFrame; used for weighted metrics such as AUC/KS when there is no grouping.
It requires |
None
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
Grouped performance evaluation summary table: one row per given dataset ( |
Notes
With weight_col and without oot_grp_name the call is delegated to the weighted implementation: it needs
scr_name (with model and feature_cols instead it fails with KeyError), only uses pct_bins as the
number of bins, ignores the figure, report, display and binning arguments, and returns a narrower table (index,
dataset, DATASET, AUC, KS, LIFT, IV, N, N_RAW, avgTrue, avgScore).
With oot_grp_name the figure, the report and the display are produced once per group, so fig_save_path and
rpt_save_path are overwritten by every group: the files only hold the last group (and the report has no group
column).
Source code in Modeling_Tool/Eval/Model_Eval_Tool.py
1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 | |
cross_risk
¶
cross_risk(data, score_list, dep, nbins, agg_col=None, precision=5, min_bin_prop=0.05, include_missing=False, equal_freq=True, binning_numeric=[True, True], agg_func='mean', chi2_method=False, chi2_p=0.95, init_equi_bins=100, fillna=-999999, spec_values=[], tree_binning=False, random_state=42, weight_col=None, sample_weight=None, wgt_col=None)
Create a cross-risk table.
After binning the two score columns, compute the aggregated risk value of each cross group. Numeric variables can be binned automatically.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame
|
Input data table. |
required |
score_list
|
list
|
List of score columns, of length 2. |
required |
dep
|
str
|
Name of the target variable. |
required |
nbins
|
int or list
|
Number of bins (an integer or a list of length 2). |
required |
agg_col
|
str
|
Name of the column to aggregate; defaults to |
None
|
precision
|
int or list
|
Precision of the bin boundary values. |
5
|
min_bin_prop
|
float or list
|
Minimum proportion of samples per bin. |
0.05
|
include_missing
|
bool
|
Whether missing scores are binned. True fills them with |
False
|
equal_freq
|
bool
|
True for equal-frequency binning. |
True
|
binning_numeric
|
(list, tuple or bool)
|
Whether to bin each of the two columns when it is numeric ( |
[True, True]
|
agg_func
|
(str, callable, tuple or dict)
|
Aggregation function. Regular usage is the same as the The ratio of two aggregated columns can also be computed directly:
When |
'mean'
|
chi2_method
|
bool
|
Whether to use chi-square binning. |
False
|
chi2_p
|
float
|
Significance level of the chi-square test. |
0.95
|
init_equi_bins
|
int
|
Initial number of equal-frequency bins. |
100
|
fillna
|
any
|
Fill value for missing values. |
-999999
|
spec_values
|
list
|
List of special values. |
[]
|
tree_binning
|
bool
|
Whether to use decision-tree binning. |
False
|
random_state
|
int
|
Random seed. |
42
|
weight_col
|
str
|
Column in |
None
|
sample_weight
|
array - like
|
Explicit per-row weights; must align with |
None
|
wgt_col
|
str
|
Alias for |
None
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
Cross-risk table. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the ratio syntax is used without a numerator and a denominator (for |
TypeError
|
If |
Notes
If the first score column is not binned (it is not numeric, or binning_numeric[0] is False), the helper columns
_bin_num1 and _bin_range1 (and _bin_num2 and _bin_range2 when the second score column is not binned
either) are added to the DataFrame passed as data.
Examples:
Source code in Modeling_Tool/Eval/Model_Eval_Tool.py
1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 | |
get_gains_table_by_cust_metrics
¶
get_gains_table_by_cust_metrics(data, dep, nbins=10, precision=5, min_bin_prop=0.05, include_missing=True, score=None, model=None, varlist=None, equal_freq=True, chi2_method=False, grp_name=None, min_data_size=100, grp_colname=None, sync_range=True, chi2_p=0.95, init_equi_bins=100, fillna=-999999, spec_values=[], tree_binning=False, random_state=42, ascending=True, eval_metrics=['age', 'monthly_income', 'education'], metric_agg_func='mean', withSummary=False)
Compute the grouped Gains table with custom metrics.
Split the data into groups by the grouping column and compute the custom-metric Gains table of each group separately. The Gains table contains the basic statistics as well as the aggregated values of the custom metrics.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame
|
Input data table. |
required |
dep
|
str
|
Name of the target variable. |
required |
nbins
|
int
|
Number of bins. |
10
|
precision
|
int
|
Precision of the bin boundary values. |
5
|
min_bin_prop
|
float
|
Minimum proportion of samples per bin. |
0.05
|
include_missing
|
bool
|
Whether missing scores are binned. True fills them with |
True
|
score
|
str
|
Name of the score column. |
None
|
model
|
sklearn-like model
|
Machine learning model. |
None
|
varlist
|
list
|
List of model features. |
None
|
equal_freq
|
bool
|
True for equal-frequency binning. |
True
|
chi2_method
|
bool
|
Whether to use chi-square binning. |
False
|
grp_name
|
str
|
Name of the grouping column. |
None
|
min_data_size
|
int
|
Minimum number of samples per group. |
100
|
grp_colname
|
str
|
Name of the group column in the output. |
None
|
sync_range
|
bool
|
Whether to synchronize the bin boundaries across groups. |
True
|
chi2_p
|
float
|
Significance level of the chi-square test. |
0.95
|
init_equi_bins
|
int
|
Initial number of equal-frequency bins. |
100
|
fillna
|
any
|
Fill value for missing values. |
-999999
|
spec_values
|
list
|
List of special values. |
[]
|
tree_binning
|
bool
|
Whether to use decision-tree binning. |
False
|
random_state
|
int
|
Random seed. |
42
|
ascending
|
bool
|
Whether the bin order is ascending. |
True
|
eval_metrics
|
list
|
List of custom metrics to compute. |
["age", "monthly_income", "education"]
|
metric_agg_func
|
str or callable
|
Aggregation function for the custom metrics. |
"mean"
|
withSummary
|
bool
|
Whether to include an overall summary row. |
False
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
Grouped Gains table with custom metrics: the compact Gains columns ( |
Notes
eval_metrics names the columns of data that are aggregated in every bin with metric_agg_func; its default
refers to the columns of a legacy dataset, so always pass your own list. The function has no weight argument, and its
default ascending=True differs from that of get_gains_table (False).
Source code in Modeling_Tool/Eval/Model_Eval_Tool.py
1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 | |
tie_score_rate
¶
Compute the score tie rate.
Compute the proportion of non-unique score values: one minus the number of distinct score values divided by the number of rows (in a group of rows that share a score, all the rows but one are counted).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame
|
Input data table. |
required |
score
|
str
|
Name of the score column. |
required |
Returns:
| Type | Description |
|---|---|
float
|
Score tie rate (between 0 and 1). |
Examples:
>>> tie_score_rate(data, 'score')
0.15 # means that the number of distinct scores is 85% of the number of rows
Source code in Modeling_Tool/Eval/Model_Eval_Tool.py
score_unique_rate
¶
Compute the score unique rate.
Compute the proportion of unique score values in the total number of samples.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame
|
Input data table (this parameter is retained but not used). |
required |
score
|
array - like
|
Score column or array. |
required |
Returns:
| Type | Description |
|---|---|
float
|
Score unique rate (between 0 and 1). |
Examples:
>>> score_unique_rate(data, data['score'])
0.85 # means that the scores of 85% of the samples are unique
Source code in Modeling_Tool/Eval/Model_Eval_Tool.py
Score Comparison and Evaluation Pipeline: Evaluation_Tool¶
Evaluation_Tool
¶
Model Evaluation Tool - Optimized Version
This module provides classes and functions for model evaluation, performance comparison, and gains analysis. It includes utilities for calculating various metrics and generating cross-risk summaries.
Author: Matrix Agent
EvaluationPipeline
¶
Chainable pipeline object for slice-by-slice evaluation.
Conditions are added by chaining .group_by() and .subset_by(), and the
pipeline is executed with .apply(func).
func may return a pandas.DataFrame or a dict whose values are DataFrames.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
m_eval
|
Model_Evaluation_Tool
|
Evaluation object whose methods |
required |
data
|
DataFrame
|
Data to slice. Default is None, i.e. |
None
|
Attributes:
| Name | Type | Description |
|---|---|---|
m_eval |
Model_Evaluation_Tool
|
The evaluation object. |
original_data |
DataFrame
|
The data that is sliced. |
steps |
list of dict
|
The slicing steps added so far by |
Source code in Modeling_Tool/Eval/Evaluation_Tool.py
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 | |
group_by
¶
Add a step that splits the data by the values of a column.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
group_name
|
str
|
Name of the column to group by. |
required |
min_size
|
int
|
Groups with fewer than |
100
|
group_var_name
|
str or None
|
Name of the result column that holds the group value. Default is None, i.e. |
None
|
Returns:
| Type | Description |
|---|---|
EvaluationPipeline
|
The pipeline itself, to allow method chaining. |
Source code in Modeling_Tool/Eval/Evaluation_Tool.py
subset_by
¶
Add a step that filters the data with a set of named conditions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
condition_dict
|
dict
|
Mapping from a subset label to a |
required |
name
|
str
|
Name of the result column that holds the subset label. |
'eval_subset'
|
min_size
|
int
|
Subsets with fewer than |
100
|
Returns:
| Type | Description |
|---|---|
EvaluationPipeline
|
The pipeline itself, to allow method chaining. |
Source code in Modeling_Tool/Eval/Evaluation_Tool.py
apply
¶
Run func on every slice and combine the results.
The steps are applied in the order in which they were added, and each step splits the output of the previous one
(group_by followed by subset_by evaluates every group once per subset). With no step, func runs once
on the whole data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
func
|
callable
|
Function to run on each slice. If it has a parameter named |
required |
**kwargs
|
Extra keyword arguments passed to |
{}
|
Returns:
| Type | Description |
|---|---|
DataFrame or dict
|
The results of all the slices concatenated, with one extra column per step that holds the group value or the
subset label (see |
Notes
An exception raised by func is logged at INFO level and the slice yields an empty result instead of
stopping the run, so an unexpectedly empty result may hide an error: call func on one slice to see it.
Source code in Modeling_Tool/Eval/Evaluation_Tool.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 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 | |
Utility_Functions
¶
Utility functions for data processing and calculations.
Source code in Modeling_Tool/Eval/Evaluation_Tool.py
valid_average
staticmethod
¶
Calculate the average of positive values in a Series.
This function filters out non-positive values (including zeros and negatives) before calculating the mean, useful for financial or count data where zero or negative values should not contribute to the average.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
Series
|
Input series of numeric values. |
required |
Returns:
| Type | Description |
|---|---|
float
|
Rounded average of positive values, or 0 if no valid values exist. |
Examples:
Source code in Modeling_Tool/Eval/Evaluation_Tool.py
Model_Evaluation_Tool
¶
A comprehensive tool for model evaluation, performance comparison, and gains analysis.
This class provides methods for: - Base score calculation and correlation analysis - Model performance comparison across multiple metrics - Gains table generation and analysis - Cross-risk analysis - Multi-dimensional evaluation with subsets and groupings
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame
|
Input data containing features and target variables. |
required |
dep
|
str
|
Name of the dependent/target variable. |
required |
comp_scrlist
|
list
|
List of comparison score column names. |
required |
model
|
object
|
Trained model with predict_proba method. Default is None. |
None
|
base_score
|
str
|
Name of the base score column. Default is None. |
None
|
min_data_size
|
int
|
Minimum data size threshold: the minimum number of rows of a group in |
500
|
equal_freq
|
bool
|
Whether to use equal frequency binning. Default is True. |
True
|
precision
|
int
|
Decimal precision for rounding. Default is 5. |
5
|
chi2_method
|
bool
|
Whether to use chi-square method. Default is False. |
False
|
chi2_p
|
float
|
Chi-square p-value threshold. Default is 0.999. |
0.999
|
init_equi_bins
|
int
|
Initial number of equal frequency bins. Default is 500. |
500
|
tree_binning
|
bool
|
Whether to use tree-based binning. Default is False. |
False
|
random_seed
|
int
|
Random seed for reproducibility. Default is 3407. |
3407
|
nbins
|
int
|
Number of bins for analysis. Default is 10. |
10
|
min_bin_prop
|
float
|
Minimum proportion for each bin. Default is 0.05. |
0.05
|
include_missing
|
bool
|
Whether to include missing values. Default is True. |
True
|
missing_rate_ref
|
int or float
|
Reference value for missing rate: the fill value for missing values, passed as |
-99999999
|
excel_path
|
str
|
Path for Excel output. Default is None. It is only stored as an attribute: no method of this class writes an Excel file. |
None
|
fillna
|
any
|
Fill value for missing scores in the Gains-table binning of |
-999999
|
spec_values
|
list
|
Special score values that get their own bins in |
None
|
cross_agg_dict
|
dict
|
Columns aggregated in the cells of |
None
|
subset_condition_dict
|
dict
|
Subsets read by |
None
|
eval_ylabels
|
list of str
|
Target columns evaluated by |
None
|
grp_namelist
|
list of str
|
Grouping columns evaluated by |
None
|
gains_display_metric_list
|
list of str
|
Gains-table columns kept by |
None
|
weight_col
|
str
|
Name of the sample weight column in |
None
|
positive_score_only
|
bool
|
Whether |
True
|
Attributes:
| Name | Type | Description |
|---|---|---|
data |
DataFrame
|
The input data (may be modified during processing). |
dep |
str
|
Target variable name. |
base_score |
str or None
|
Name of the base score column. |
comp_scrlist |
list
|
List of comparison score names. |
eval_ylabels |
list
|
Labels for y-axis evaluation. |
gains_display_metric_list |
list
|
Metrics to display in gains summary. |
Notes
Every constructor parameter is also stored as an attribute of the same name, except random_seed, which is stored as
seed; udf holds a Utility_Functions instance. cross_agg_dict, subset_condition_dict,
eval_ylabels and grp_namelist default to legacy values tied to one production dataset, so override them
whenever you use the methods that read them. get_cross_risk_summary also needs a flow_id column in data.
Source code in Modeling_Tool/Eval/Evaluation_Tool.py
312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 | |
get_base_score
¶
Calculate base model scores using the provided model.
This method uses the model's predict_proba method to generate scores for the input data and optionally displays correlation analysis.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
scorename
|
str
|
Name for the score column. Default is 'base_model_score'. |
'_base_model_score_'
|
disp
|
bool
|
Whether to display intermediate results. Default is False. |
False
|
Returns:
| Type | Description |
|---|---|
Model_Evaluation_Tool
|
Returns self for method chaining. |
Raises:
| Type | Description |
|---|---|
AttributeError
|
If model is None or lacks required attributes. |
Notes
The model must expose feature_names_in_: those columns are passed to predict_proba. As a side effect,
self.data is replaced by a copy that has the new score column and self.base_score is set to scorename.
disp=True needs IPython.
Source code in Modeling_Tool/Eval/Evaluation_Tool.py
get_score_correlation
¶
Calculate correlation matrix between score columns.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
score_list
|
list
|
List of score column names. If None, uses base_score and comp_scrlist. |
None
|
method
|
str
|
Correlation method ('pearson', 'spearman', 'kendall'). Default is 'pearson'. |
'pearson'
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
Correlation summary in long format with columns: 'base', 'compare', 'corr'. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Notes
Only the rows in which every score of score_list is greater than 0 are used (rows with a missing score are
dropped as well), whatever positive_score_only is.
Source code in Modeling_Tool/Eval/Evaluation_Tool.py
model_perf_compare
¶
model_perf_compare(data: Optional[DataFrame] = None, grp_name: Optional[str] = None, dist_bins: int = 100, pct_bins: int = 10, min_data_size: int = 50, sync_data_size: bool = True, min_bin_prop: Optional[float] = None, include_missing: Optional[bool] = None, equal_freq: Optional[bool] = None, sample_name: Optional[str] = None) -> DataFrame
Compare model performance across different scores.
This method calculates performance metrics (AUC, KS, etc.) for the base score
and all comparison scores via PerformanceEvaluator, optionally filtering
by group.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame
|
Data to use. If None, uses self.data. |
None
|
grp_name
|
str
|
Group name column for stratification. Every score is then evaluated separately for each group value (the
result gains a column named |
None
|
dist_bins
|
int
|
Number of distribution bins. Default is 100. |
100
|
pct_bins
|
int
|
Number of percentile bins. Default is 10. |
10
|
min_data_size
|
int
|
Minimum number of rows of a group for it to be evaluated; it only matters when |
50
|
sync_data_size
|
bool
|
Whether every score, the base score included, is evaluated on the same rows: the rows with an observed target where every score is valid (see Notes). False evaluates each score on its own valid rows. Default is True. |
True
|
min_bin_prop
|
float
|
Minimum bin proportion. Defaults to the instance setting. |
None
|
include_missing
|
bool
|
Whether to include missing values in performance binning.
Defaults to |
None
|
equal_freq
|
bool
|
Use equal-frequency binning. Defaults to the instance setting. |
None
|
sample_name
|
str
|
Label applied to the evaluated dataset and emitted in the result's
|
None
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
Performance comparison results sorted by score order: the |
Notes
A score is valid in a row when it is a finite number and, with positive_score_only=True, greater than 0; rows
whose target is missing are never used. The column N_OWN gives the number of rows (not weights) in which the
score alone is valid, so with sync_data_size=True it shows how much each score's coverage was narrowed to the
common rows. A score without any valid row is left out of the result with a UserWarning instead of emptying
the common rows of the others; when the scores have valid rows but none in common, a UserWarning is issued
and an empty DataFrame returned. With weight_col set on the instance (and no grp_name) the weighted,
narrower summary is returned.
Source code in Modeling_Tool/Eval/Evaluation_Tool.py
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 | |
get_gains_summary
¶
get_gains_summary(data: Optional[DataFrame] = None, grp_name: Optional[str] = None, disp: bool = True, grp_disp_metric: List[str] = None, grp_nbins: int = 5, withSummary: bool = True, add_func: Optional[Callable] = None, sync_range: bool = True, spec_values=None, include_missing: Optional[bool] = None, fillna=None) -> DataFrame
Generate gains summary table for score analysis.
This method creates gains tables via GainsTableCalculator, showing the
distribution of targets across score bins, with optional group stratification.
Custom metrics can be injected through add_func.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame
|
Data to use. If None, uses self.data. |
None
|
grp_name
|
str
|
Group name for stratified analysis: one Gains table per group value, stacked, with the group value in a column
named |
None
|
disp
|
bool
|
Whether to display, with |
True
|
grp_disp_metric
|
list
|
Metrics shown by |
None
|
grp_nbins
|
int
|
Number of bins for grouped analysis. Default is 5. |
5
|
withSummary
|
bool
|
Include summary row. Default is True. It is not applied with |
True
|
add_func
|
callable
|
Custom metric function merged into each gains table. When it is given, all the columns of the Gains table are
returned instead of only |
None
|
sync_range
|
bool
|
Synchronize bin ranges across the groups (used with |
True
|
spec_values
|
list
|
Special values to treat separately during binning. Default is None, i.e. the instance setting. |
None
|
include_missing
|
bool
|
Whether to include missing values. Defaults to the instance setting. |
None
|
fillna
|
any
|
Missing-value fill for score binning. Defaults to the instance setting. |
None
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
Gains summary results with score names: the Gains tables of the base score and of every comparison score,
stacked, with the bin columns |
Notes
When the instance has a weight_col and grp_name is None, the weighted Gains table is returned (N is the
sum of the weights and N_RAW the number of rows), with the add_func columns and the summary row when they
are asked for.
Source code in Modeling_Tool/Eval/Evaluation_Tool.py
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 | |
get_cross_risk_summary
¶
get_cross_risk_summary(cross_agg_dict: Optional[Dict] = None, nbins: int = 5, equal_freq: Optional[bool] = None, disp: bool = True, spec_values=None, binning_numeric=None) -> DataFrame
Generate cross-risk analysis summary between base and comparison scores.
This method creates a comprehensive cross-tabulation showing risk metrics across different score ranges for both base and comparison scores.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cross_agg_dict
|
dict
|
Dictionary of column names and aggregation functions, as |
None
|
nbins
|
int
|
Number of bins. Default is 5. |
5
|
equal_freq
|
bool
|
Use equal frequency binning. If None, uses self.equal_freq. |
None
|
disp
|
bool
|
Whether to display, with |
True
|
spec_values
|
list
|
Special values to keep separate during binning. Default is None, i.e. the instance setting. |
None
|
binning_numeric
|
bool or list/tuple of bool
|
Whether numeric score columns should be binned before cross-risk aggregation. If None, defaults to [True, True] for backward compatibility. Passing a bool applies the same setting to both base and comparison score. |
None
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
Cross-risk summary with base score range, comparison score range, and metrics, in long format with the columns
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
TypeError
|
If |
Notes
For every comparison score only the rows in which both the base score and that score are greater than 0 are used,
whatever positive_score_only is (rows with a missing score are therefore dropped too). The summary is
unweighted: weight_col is not used.
Source code in Modeling_Tool/Eval/Evaluation_Tool.py
1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 | |
multi_subset_wrapper
¶
multi_subset_wrapper(condition_dict: Optional[Dict[str, str]] = None, subset_var_name: str = 'eval_subset', func: Optional[Callable] = None, min_subset_size=10, **kwargs) -> DataFrame
Apply evaluation function across multiple data subsets.
This method iterates over predefined subset conditions, filters the data accordingly, and applies the evaluation function to each subset.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
condition_dict
|
dict
|
Dictionary mapping subset names to query conditions ( |
None
|
subset_var_name
|
str
|
Column name for subset identifier in results. Default is 'eval_subset'. |
'eval_subset'
|
func
|
callable
|
Function to apply to each subset. If None, uses model_perf_compare. |
None
|
min_subset_size
|
int
|
Only subsets with more than this many rows are evaluated. Default is 10. |
10
|
**kwargs
|
Additional keyword arguments passed to the evaluation function. |
{}
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
Combined results from all subsets, with the subset label in the column |
Notes
self.data is replaced by the subset while func runs and restored afterwards (it is not restored if func
raises an exception).
Source code in Modeling_Tool/Eval/Evaluation_Tool.py
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 | |
multi_ylabel_wrapper
¶
multi_ylabel_wrapper(ylabels: Optional[List[str]] = None, ylabel_var_name: str = 'eval_ylabel', eval_func: Optional[Callable] = None, **kwargs) -> DataFrame
Apply evaluation function across multiple target labels.
This method iterates over different target/label columns, temporarily updating the dependent variable for each iteration.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ylabels
|
list
|
List of target column names. If None, uses self.eval_ylabels. |
None
|
ylabel_var_name
|
str
|
Column name for label identifier in results. Default is 'eval_ylabel'. |
'eval_ylabel'
|
eval_func
|
callable
|
Function to apply for each label. If None, uses model_perf_compare. |
None
|
**kwargs
|
Additional keyword arguments passed to the evaluation function. |
{}
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
Combined results from all labels, with the label in the column |
Notes
For each label the rows in which the label is missing are dropped, and self.dep and self.data are replaced
while eval_func runs and restored afterwards (they are not restored if eval_func raises an exception).
Source code in Modeling_Tool/Eval/Evaluation_Tool.py
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 | |
multi_group_wrapper
¶
multi_group_wrapper(group_name: Optional[str] = None, group_var_name: str = 'group_name', group_eval_func: Optional[Callable] = None, min_subset_size: int = 10, **kwargs) -> DataFrame
Apply evaluation function across multiple groups.
This method splits data by a grouping column and applies the evaluation function to each group separately.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
group_name
|
str
|
Column name to group by. If None, |
None
|
group_var_name
|
str
|
Column name for group identifier in results. Default is 'group_name'. |
'group_name'
|
group_eval_func
|
callable
|
Function to apply to each group. If None, uses model_perf_compare. |
None
|
min_subset_size
|
int
|
Only groups with more than this many rows are evaluated. Default is 10. |
10
|
**kwargs
|
Additional keyword arguments passed to the evaluation function. |
{}
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
Combined results from all groups, with the group value in the column |
Notes
The groups are the distinct non-missing values of group_name in order of appearance, and the rows are selected
by value, so numeric group columns and values containing quotes work. self.data is replaced by the group while
group_eval_func runs and restored afterwards (it is not restored if the function raises an exception).
Source code in Modeling_Tool/Eval/Evaluation_Tool.py
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 | |
multi_dim_eval
¶
multi_dim_eval(condition_dict: Optional[Dict[str, str]] = None, eval_ylabels: Optional[List[str]] = None, grp_namelist: Optional[List[str]] = None, eval_func: Optional[Callable] = None, subset_var_name: str = 'eval_subset', ylabel_var_name: str = 'eval_ylabel', var_name: str = 'group_name', value_name: str = 'group_value', **kwargs) -> DataFrame
Perform multi-dimensional evaluation across subsets, labels, and groups.
This method combines multi_subset_wrapper and multi_ylabel_wrapper to evaluate model performance across different dimensions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
condition_dict
|
dict
|
Subset conditions. If None, uses self.subset_condition_dict. |
None
|
eval_ylabels
|
list
|
Target labels. If None, uses self.eval_ylabels. |
None
|
grp_namelist
|
list
|
Group columns. If None, uses self.grp_namelist. |
None
|
eval_func
|
callable
|
Evaluation function. If None, uses model_perf_compare. It is called for every subset, label and group column;
the group column is passed to it as |
None
|
subset_var_name
|
str
|
Column name for subset identifier. Default is 'eval_subset'. |
'eval_subset'
|
ylabel_var_name
|
str
|
Column name for label identifier. Default is 'eval_ylabel'. |
'eval_ylabel'
|
var_name
|
str
|
Column name for group name in results. Default is 'group_name'. |
'group_name'
|
value_name
|
str
|
Column name for group value in results. Default is 'group_value'. |
'group_value'
|
**kwargs
|
Additional keyword arguments, passed on to |
{}
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
Multi-dimensional evaluation results: the results of |
Notes
If eval_func has no grp_name parameter, the same evaluation is simply repeated for each entry of
grp_namelist (no grouping is done). With the default eval_func every call is grouped, so the evaluation is
unweighted.
Source code in Modeling_Tool/Eval/Evaluation_Tool.py
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 | |
cross_perf_eval
¶
cross_perf_eval(bad_list: List[str], scr_list: List[str], data: Optional[DataFrame] = None, eval_metric: List[str] = None, melt: bool = True) -> DataFrame
Cross-evaluate model performance across multiple bad flags and scores.
This method calculates performance metrics for all combinations of bad flags and scores, useful for comparing model behavior across different definitions of "bad" outcomes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
bad_list
|
list
|
List of bad/negative outcome column names. |
required |
scr_list
|
list
|
List of score column names. |
required |
data
|
DataFrame
|
Data to use. If None, uses self.data. |
None
|
eval_metric
|
list
|
Metrics to extract. If None, uses ['AUC', 'KS', 'N']. |
None
|
melt
|
bool
|
Whether to melt the pivot table. Default is True. |
True
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
Cross performance evaluation results. With |
Notes
The rows in which a label is missing or a score is not positive are dropped. The bins come from the instance
(nbins for both the distribution and the percentile bins, precision and min_bin_prop) and the
evaluation is unweighted.
Source code in Modeling_Tool/Eval/Evaluation_Tool.py
1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 | |
run_variable_analysis_summary
¶
run_variable_analysis_summary(varlist: List[str], data: Optional[DataFrame] = None, dep: Optional[str] = None, nbins: Optional[int] = None, equal_freq: Optional[bool] = None, min_bin_prop: Optional[float] = None, precision: Optional[int] = None, chi2_method: Optional[bool] = None, chi2_p: Optional[float] = None, init_equi_bins: Optional[int] = None, tree_binning: Optional[bool] = None, include_missing: Optional[bool] = None, missing_rate_ref: Optional[Union[int, float]] = None, seed: Optional[int] = None, spec_values=[]) -> DataFrame
Run comprehensive variable analysis and generate summary report.
This method performs binning analysis on specified variables, calculating metrics like IV (Information Value), KS and Lift of each variable.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
varlist
|
list
|
List of variable names to analyze. |
required |
data
|
DataFrame
|
Data to use. If None, uses self.data. |
None
|
dep
|
str
|
Target variable name. If None, uses self.dep. |
None
|
nbins
|
int
|
Number of bins. If None, uses self.nbins. |
None
|
equal_freq
|
bool
|
Use equal frequency binning. If None, uses self.equal_freq. |
None
|
min_bin_prop
|
float
|
Minimum bin proportion. If None, uses self.min_bin_prop. |
None
|
precision
|
int
|
Decimal precision. If None, uses self.precision. |
None
|
chi2_method
|
bool
|
Use chi-square method. If None, uses self.chi2_method. |
None
|
chi2_p
|
float
|
Chi-square p-value. If None, uses self.chi2_p. |
None
|
init_equi_bins
|
int
|
Initial equal bins. If None, uses self.init_equi_bins. |
None
|
tree_binning
|
bool
|
Use tree binning. If None, uses self.tree_binning. |
None
|
include_missing
|
bool
|
Include missing values. If None, uses self.include_missing. |
None
|
missing_rate_ref
|
int or float
|
Missing reference. If None, uses self.missing_rate_ref. |
None
|
seed
|
int
|
Random seed. If None, uses self.seed. |
None
|
spec_values
|
list
|
Special values that get their own bins in the analysis. Unlike the other arguments, the default is not taken from the instance. |
[]
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
Variable analysis summary with IV and other metrics: one row per variable, sorted by decreasing IV, with the
columns |
Notes
Before the analysis the missing values of the variables in varlist are filled with missing_rate_ref (in a
copy of the data). The summary is unweighted.
Source code in Modeling_Tool/Eval/Evaluation_Tool.py
1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 | |
pipe
¶
Return an EvaluationPipeline for chained group and subset evaluation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame
|
Data to evaluate. Defaults to |
None
|
Returns:
| Type | Description |
|---|---|
EvaluationPipeline
|
|
Source code in Modeling_Tool/Eval/Evaluation_Tool.py
Curves, Summaries, and Figures: evaluate_model¶
evaluate_model
¶
timeit_decorator
¶
Decorator that times every call of func.
The elapsed time is measured but not reported (the line that prints it is commented out), so the wrapped function
behaves exactly like func: same arguments, same return value, and the metadata is preserved by functools.wraps.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
func
|
Function to wrap. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
wrapper |
callable
|
The wrapped function. |
Source code in Modeling_Tool/Eval/evaluate_model.py
calc_pr
¶
Compute the statistics of the P-R curve. Based on sklearn.metrics.precision_recall_curve.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
y_true
|
Sequence of actual sample labels; only 0/1 values are accepted. |
required | |
y_score
|
Sequence of predicted probabilities. |
required | |
sample_weight
|
Per-sample weights aligned with |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
pr_df |
DataFrame
|
Dataset of PR statistics such as precision, recall, and thresholds. |
Notes
The columns are precision, recall, thresholds and, on the unweighted path only, thresholds_percentile
(percentage of scores at or below the threshold). The last row has no threshold (NaN).
Source code in Modeling_Tool/Eval/evaluate_model.py
summarize_pr
¶
Summarize the P-R curve.
The statistics are:
- The break-even point (BEP) threshold and the corresponding precision, recall, and other statistics.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
pr_df
|
Dataset of PR statistics such as precision, recall, and thresholds. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
pr_info |
dict
|
Dictionary of P-R curve summary statistics: |
Source code in Modeling_Tool/Eval/evaluate_model.py
plot_pr_curve
¶
Plot the P-R curve.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
pr_dfs
|
PR datasets for one or more scores, as key-value pairs in the format {name: pr_df}. |
required | |
square_figsize
|
Side length of the square figure in inches. Defaults to 8. |
8
|
|
to_show
|
Whether to display the figure. Defaults to True. |
True
|
|
save_path
|
File path to save the resulting figure. Defaults to None, i.e. the figure is not saved. |
None
|
Notes
One entry draws a single curve with its break-even point (BEP); several entries are overlaid, and at most three can be
drawn together (the palette has three colors, a fourth raises IndexError).
Source code in Modeling_Tool/Eval/evaluate_model.py
calc_roc
¶
Compute the statistics of the ROC curve. Based on sklearn.metrics.roc_curve.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
y_true
|
Sequence of actual sample labels; only 0/1 values are accepted. |
required | |
y_score
|
Sequence of predicted probabilities. |
required | |
sample_weight
|
Per-sample weights aligned with |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
roc_df |
DataFrame
|
Dataset of ROC statistics such as TPR, FPR, and thresholds. |
Notes
The columns are fpr, tpr, thresholds and thresholds_percentile (percentage of the samples, or of the total
weight when weighted, with a score at or below the threshold). The weighted result also has FPR, TPR and KS
(abs(tpr - fpr)). Rows whose label, score or weight is not finite are dropped; if no row is left, an empty
DataFrame with these columns is returned.
Source code in Modeling_Tool/Eval/evaluate_model.py
summarize_roc
¶
Summarize the ROC curve.
The statistics are:
- AUC
- KS and its corresponding threshold
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
roc_df
|
Dataset of ROC statistics such as TPR, FPR, and thresholds. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
roc_info |
dict
|
Dictionary of ROC curve summary statistics: |
Source code in Modeling_Tool/Eval/evaluate_model.py
plot_ks_curve
¶
Plot the KS curve. Only the KS curve of a single score can be plotted.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
roc_df
|
Dataset of ROC statistics such as TPR, FPR, and thresholds. |
required | |
square_figsize
|
Side length of the square figure in inches. Defaults to 8. |
8
|
|
to_show
|
Whether to display the figure. Defaults to True. |
True
|
|
save_path
|
File path to save the resulting figure. Defaults to None, i.e. the figure is not saved. |
None
|
Source code in Modeling_Tool/Eval/evaluate_model.py
plot_roc_curve
¶
plot_roc_curve(roc_dfs, square_figsize=8, fontdicts=fontdicts['main'], to_show=True, save_path=None)
Plot the ROC curve. Curves for a single score or for multiple scores can be plotted.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
roc_dfs
|
Dictionary of ROC statistics for one or more scores. Key-value pairs in the format {name: roc_df}. |
required | |
square_figsize
|
Side length of the square figure in inches. Defaults to 8. |
8
|
|
fontdicts
|
Dictionary of font settings for the plot, in the format of the module-level presets |
fontdicts['main']
|
|
to_show
|
Whether to display the figure. Defaults to True. |
True
|
|
save_path
|
File path to save the resulting figure. Defaults to None, i.e. the figure is not saved. |
None
|
Notes
One entry draws a single ROC curve with its KS gap; several entries are overlaid, and at most three can be drawn
together (the palette has three colors, a fourth raises IndexError).
Source code in Modeling_Tool/Eval/evaluate_model.py
plot_kde_curve
¶
plot_kde_curve(y_true, y_score_dict, bins=20, square_figsize=8, fontdicts=fontdicts['main'], to_show=True, save_path=None)
Plot the kernel density estimate (KDE) curves of the scores.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
y_true
|
Sequence of actual sample labels; only 0/1 values are accepted. |
required | |
y_score_dict
|
Dictionary of one or more score sequences, as key-value pairs in the format {name: Score}. |
required | |
bins
|
Number of histogram bins; it also sets the bandwidth factor of the KDE ( |
20
|
|
square_figsize
|
Side length of the square figure in inches. Defaults to 8. |
8
|
|
fontdicts
|
Dictionary of font settings for the plot, in the format of the module-level presets |
fontdicts['main']
|
|
to_show
|
Whether to display the figure. Defaults to True. |
True
|
|
save_path
|
File path to save the resulting figure. Defaults to None, i.e. the figure is not saved. |
None
|
Notes
One score draws a histogram plus the KDE curves of the negative and the positive samples; several scores draw one KDE
curve per score and at most three can be drawn together (the palette has three colors, a fourth raises IndexError).
The plot is unweighted: there is no weight argument.
Source code in Modeling_Tool/Eval/evaluate_model.py
calc_equid_dist
¶
Divide the score into equal-width bins and compute the statistics of each bin.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
y_true
|
Sequence of actual sample labels; only 0/1 values are accepted. |
required | |
y_score
|
Sequence of predicted probabilities. |
required | |
y_group
|
Sequence of data groups. Defaults to None, i.e. no groups. |
None
|
|
bins
|
Number of bins. |
10
|
|
sample_weight
|
Per-sample weights aligned with |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
dist_df |
DataFrame
|
Dataset of per-bin statistics after equal-width binning: one row per bin (per group and bin when |
Notes
The bin edges follow powers of ten: they run from 0 (or, for negative scores, from the negative power of ten at or
below the minimum score) to the power of ten at or above the maximum score, so probabilities are cut at 0, 0.1, ..., 1
when bins=10.
With sample_weight the call is delegated to the weighted Gains-table implementation. The result is then a Gains
table (columns MIN, MAX, N, N_RAW, AVG_BAD, LIFT, ... indexed by _bin_num and
_bin_range) built from bins equal-weight bins, not an equal-width table.
Source code in Modeling_Tool/Eval/evaluate_model.py
calc_equid_pct
¶
Divide the score into strictly equal-frequency bins and compute the statistics of each bin.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
y_true
|
Sequence of actual sample labels; only 0/1 values are accepted. |
required | |
y_score
|
Sequence of predicted probabilities. |
required | |
y_group
|
Sequence of data groups. Defaults to None, i.e. no groups. |
None
|
|
bins
|
Number of bins. |
10
|
|
ascending
|
Whether to sort y_score in ascending order. Defaults to True, i.e. the first bin holds the lowest scores; with False it holds the highest scores. |
True
|
|
sample_weight
|
Per-sample weights aligned with |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
pct_df |
DataFrame
|
Dataset of per-bin statistics after equal-frequency binning. It has the columns of |
Notes
The rows are ranked by score and cut into bins bins of int(n / bins) rows each; the remainder goes to the last
bin.
With sample_weight the call is delegated to the weighted Gains-table implementation. The result is then a Gains
table (columns MIN, MAX, N, N_RAW, AVG_BAD, LIFT, ... indexed by _bin_num and
_bin_range) built from bins equal-weight bins (bin 1 holds the lowest scores when ascending=True), not the
table described above.
Source code in Modeling_Tool/Eval/evaluate_model.py
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 | |
calc_fixed_pct
¶
Divide the score by fixed score boundaries and compute the statistics of each bin.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
y_true
|
Sequence of actual sample labels; only 0/1 values are accepted. |
required | |
y_score
|
Sequence of predicted probabilities. |
required | |
y_group
|
Sequence of data groups. Defaults to None, i.e. no groups. |
None
|
|
bin_edges
|
Fixed bin edges, usually taken from a benchmark dataset. Required unless |
None
|
|
ascending
|
Whether to bin y_score in ascending order. Defaults to True: the percentile labels grow with the score; with False they are reversed (the interval with the lowest scores gets the largest label). |
True
|
|
sample_weight
|
Per-sample weights aligned with |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
pct_df |
DataFrame
|
Dataset of per-bin statistics after fixed binning. It has the same columns as the result of |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Notes
The intervals are closed on the right, (edge_k, edge_k+1]. A score equal to the lowest edge, or outside all the
edges, falls in no bin and is left out of the table, although it still counts in the totals behind proportion and
capture_rate.
With sample_weight the call is delegated to the weighted Gains-table implementation, which does not use
bin_edges: the result is a Gains table (columns MIN, MAX, N, N_RAW, AVG_BAD, LIFT, ...)
with 10 equal-weight bins, whatever edges are passed.
Source code in Modeling_Tool/Eval/evaluate_model.py
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 | |
summarize_pct
¶
Summarize the equal-frequency bins.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
pct_df
|
Dataset of per-bin statistics after equal-frequency binning. |
required | |
ascending
|
Score order of the rows of |
True
|
Returns:
| Name | Type | Description |
|---|---|---|
pct_info |
dict
|
Dictionary of equal-frequency binning summary statistics: |
Source code in Modeling_Tool/Eval/evaluate_model.py
plot_dist_curve
¶
plot_dist_curve(dist_dfs, square_figsize=8, fontdicts=fontdicts['main'], to_show=True, save_path=None)
Plot the score distribution curve.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dist_dfs
|
Per-bin statistics datasets (equal-width binning, same number of bins) for one or more scores, as key-value pairs in the format {name: dist_df}. |
required | |
square_figsize
|
Side length of the square figure in inches. Defaults to 8. |
8
|
|
fontdicts
|
Dictionary of font settings for the plot, in the format of the module-level presets |
fontdicts['main']
|
|
to_show
|
Whether to display the figure. Defaults to True. |
True
|
|
save_path
|
File path to save the resulting figure. Defaults to None, i.e. the figure is not saved. |
None
|
Notes
One entry draws the proportion of each bin as bars together with the target rate of the bin (the bars are stacked by
group when the table has a y_group column); several entries are overlaid, and at most three can be drawn together
(the palette has three colors, a fourth raises IndexError).
Source code in Modeling_Tool/Eval/evaluate_model.py
plot_cumdist_curve
¶
plot_cumdist_curve(dist_dfs, square_figsize=8, fontdicts=fontdicts['main'], to_show=True, save_path=None)
Plot the score cumulative distribution curve.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dist_dfs
|
Per-bin statistics datasets (equal-width binning, same number of bins) for one or more scores, as key-value pairs in the format {name: dist_df}. |
required | |
square_figsize
|
Side length of the square figure in inches. Defaults to 8. |
8
|
|
fontdicts
|
Dictionary of font settings for the plot, in the format of the module-level presets |
fontdicts['main']
|
|
to_show
|
Whether to display the figure. Defaults to True. |
True
|
|
save_path
|
File path to save the resulting figure. Defaults to None, i.e. the figure is not saved. |
None
|
Notes
One entry draws the cumulative proportion of each bin as bars together with the cumulative target rate (the bars are
stacked by group when the table has a y_group column); several entries are overlaid, and at most three can be drawn
together (the palette has three colors, a fourth raises IndexError).
Source code in Modeling_Tool/Eval/evaluate_model.py
plot_pct_curve
¶
plot_pct_curve(pct_dfs, square_figsize=8, fontdicts=fontdicts['main'], to_show=True, save_path=None)
Plot the score percentile curve.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
pct_dfs
|
Per-bin statistics datasets (equal-frequency binning) for one or more scores, as key-value pairs in the format {name: pct_df}. |
required | |
square_figsize
|
Side length of the square figure in inches. Defaults to 8. |
8
|
|
fontdicts
|
Dictionary of font settings for the plot, in the format of the module-level presets |
fontdicts['main']
|
|
to_show
|
Whether to display the figure. Defaults to True. |
True
|
|
save_path
|
File path to save the resulting figure. Defaults to None, i.e. the figure is not saved. |
None
|
Notes
One entry draws the average score and the target rate of each bin against the percentile, with the overall target rate
as a reference line; several entries are overlaid (target rate only), and at most three can be drawn together (the
palette has three colors, a fourth raises IndexError).
Source code in Modeling_Tool/Eval/evaluate_model.py
plot_cumpct_curve
¶
plot_cumpct_curve(pct_dfs, square_figsize=8, fontdicts=fontdicts['main'], to_show=True, save_path=None)
Plot the cumulative score percentile curve.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
pct_dfs
|
Per-bin statistics datasets (equal-frequency binning) for one or more scores, as key-value pairs in the format {name: pct_df}. |
required | |
square_figsize
|
Side length of the square figure in inches. Defaults to 8. |
8
|
|
fontdicts
|
Dictionary of font settings for the plot, in the format of the module-level presets |
fontdicts['main']
|
|
to_show
|
Whether to display the figure. Defaults to True. |
True
|
|
save_path
|
File path to save the resulting figure. Defaults to None, i.e. the figure is not saved. |
None
|
Notes
The curves show the cumulative target rate (and, for a single entry, the cumulative average score) against the
cumulative percentile. A single entry reads a thresholds_percentile column from its table, which the result of
calc_equid_pct does not have (KeyError); several entries use the thresholds column, and at most three can be
drawn together (the palette has three colors, a fourth raises IndexError).
Source code in Modeling_Tool/Eval/evaluate_model.py
plot_gain_curve
¶
plot_gain_curve(pct_dfs, square_figsize=8, fontdicts=fontdicts['main'], to_show=True, save_path=None, ascending=False)
Plot the Gain curve (cumulative capture rate of the target against the cumulative percentile).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
pct_dfs
|
Per-bin statistics datasets (equal-frequency binning) for one or more scores, as key-value pairs in the format {name: pct_df}. |
required | |
square_figsize
|
Side length of the square figure in inches. Defaults to 8. |
8
|
|
fontdicts
|
Dictionary of font settings for the plot, in the format of the module-level presets |
fontdicts['main']
|
|
to_show
|
Whether to display the figure. Defaults to True. |
True
|
|
save_path
|
File path to save the resulting figure. Defaults to None, i.e. the figure is not saved. |
None
|
|
ascending
|
Whether the Gain chart accumulates by ascending score (True) or descending score (False). |
False
|
Notes
When a table has the columns avg_score, proportion and capture_rate, its rows are re-sorted by avg_score
according to ascending and the cumulative percentile and gain are recomputed from them; otherwise the thresholds
and gain columns are drawn as they are. A diagonal marks random selection. Several entries are overlaid, and at
most three can be drawn together (the palette has three colors, a fourth raises IndexError).
Source code in Modeling_Tool/Eval/evaluate_model.py
evaluate_performance
¶
evaluate_performance(datasets, dist_bins=20, pct_bins=10, square_figsize=5, fontdicts=fontdicts['sub'], to_show=True, save_path=None, gains_table=True, equal_freq=True, pct_bin_edges=None, sample_weight=None, ascending=None)
Plot the prediction performance evaluation chart of a single model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
datasets
|
Dictionary of datasets, as key-value pairs in the format {dataname: {'y_true': y_true, 'y_score': y_score}}.
A dataset may also carry a |
required | |
dist_bins
|
Number of equal-width bins. Defaults to 20. |
20
|
|
pct_bins
|
Number of equal-frequency bins. Defaults to 10. |
10
|
|
square_figsize
|
Side length of the square figure in inches. Defaults to 5. |
5
|
|
fontdicts
|
Dictionary of font settings for the plot. Defaults to fontdicts['sub']. |
fontdicts['sub']
|
|
to_show
|
Whether to display the figure. Defaults to True. |
True
|
|
save_path
|
File path to save the resulting figure. Defaults to None, i.e. the figure is not saved. |
None
|
|
gains_table
|
Whether the percentile panel and the Top/Btm target rates of the result are computed from the Gains-table binning
( |
True
|
|
equal_freq
|
Equal-frequency (True) or equal-width (False) binning of the Gains table; only used when |
True
|
|
pct_bin_edges
|
Fixed score bin edges for the percentile and Gain panels, usually taken from a benchmark dataset (see
|
None
|
|
sample_weight
|
Sample weights applied to every dataset that has no |
None
|
|
ascending
|
An explicit value controls the score direction of the Gains table, the percentile chart, and the Gain chart uniformly; None keeps the historical behavior (percentile ascending, Gain descending). |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
result_df |
DataFrame
|
Dataset summarizing the model evaluation metrics, one row per dataset with the columns |
Notes
Each dataset gets one row of four panels: ROC, KDE, percentile and Gain. Rows whose label, score or weight is not finite
are dropped. With weights, the metrics are weighted, the panel titles are marked Weighted and the percentile and
Gain panels are built from the equal-weight bins of the weighted Gains table.
Source code in Modeling_Tool/Eval/evaluate_model.py
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 | |
resturct_gains
¶
Convert a Gains table into the percentile-table layout used by the plotting helpers.
The Gains columns are renamed (_bin_num to thresholds, MIN to min_score, MAX to max_score,
N to n, PROP to proportion, N_BAD to sum_true, AVG_BAD to avg_true, AVG_SCORE to
avg_score, BAD_PCT_IN_EACH_BIN to capture_rate, N_CUM_BAD to cumsum_true, LIFT to lift and
CUM_BAD_PCT to gain) and the column cumavg_true is added.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
gains_table
|
Gains table as returned by |
required |
Returns:
| Type | Description |
|---|---|
DataFrame
|
One row per bin with the columns |
Source code in Modeling_Tool/Eval/evaluate_model.py
evaluate_distribution
¶
evaluate_distribution(datasets, dist_bins=10, square_figsize=5, fontdicts=fontdicts['sub'], toplot=True, save_path=None)
Plot the score distribution of a single model on multiple datasets.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
datasets
|
Dictionary of datasets, as key-value pairs in the format {dataname: {'y_true': y_true, 'y_score': y_score, 'y_group': y_group}}.
The |
required | |
dist_bins
|
Number of equal-width bins. Defaults to 10. |
10
|
|
square_figsize
|
Side length of the square figure in inches. Defaults to 5. |
5
|
|
fontdicts
|
Dictionary of font settings for the plot. Defaults to fontdicts['sub']. |
fontdicts['sub']
|
|
toplot
|
Whether to display the figure. Defaults to True. |
True
|
|
save_path
|
File path to save the resulting figure. Defaults to None, i.e. the figure is not saved. |
None
|
Returns:
| Type | Description |
|---|---|
None
|
Nothing is returned: the figure (one row of two panels per dataset, the score distribution and the cumulative score distribution) is displayed and/or saved. |
Source code in Modeling_Tool/Eval/evaluate_model.py
comparison_performance
¶
comparison_performance(datasets, pct_bins=10, square_figsize=5, fontdicts=fontdicts['sub'], to_show=True, save_path=None)
Plot the prediction performance comparison chart of multiple models.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
datasets
|
Dictionary of datasets, as key-value pairs in the format {dataname: {'y_true': y_true, 'y_score_dict': {modelname: y_score}}}.
|
required | |
pct_bins
|
Number of equal-frequency bins. Defaults to 10. |
10
|
|
square_figsize
|
Side length of the square figure in inches. Defaults to 5. |
5
|
|
fontdicts
|
Dictionary of font settings for the plot. Defaults to fontdicts['sub']. |
fontdicts['sub']
|
|
to_show
|
Whether to display the figure. Defaults to True. |
True
|
|
save_path
|
File path to save the resulting figure. Defaults to None, i.e. the figure is not saved. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
result_df |
DataFrame
|
Dataset summarizing the model evaluation metrics, one row per model and dataset with the columns |
Notes
Each dataset gets one row of three panels: ROC, percentile target rate and cumulative target rate, with one curve per
model. At most three models can be compared (the palette has three colors, a fourth raises IndexError). The
comparison is unweighted: there is no weight argument.
Source code in Modeling_Tool/Eval/evaluate_model.py
2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 | |
calc_lift_apt
¶
Compute the Lift table for a given range of Lift values.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
y_true
|
Sequence of actual sample labels; only 0/1 values are accepted. |
required | |
y_score
|
Sequence of predicted probabilities. |
required | |
start
|
Start value of the target Lift range (see Notes). |
required | |
stop
|
Stop value of the target Lift range (see Notes). |
required | |
step
|
Step size between two target Lift values. |
required | |
score_ascending
|
Whether y_score is ascending, i.e. the larger the value, the more likely y_true=1. Defaults to True. |
True
|
|
sample_weight
|
Per-sample weights aligned with |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
lift_df |
DataFrame
|
Lift table with one row per reachable target Lift and the columns |
Notes
The Lift range always has 1 at one end: with start < 1 it runs from start up to 1 and stop is ignored;
with start >= 1 it runs from 1 up to stop and start is ignored (so the table normally also contains the row
for Lift 1). The weighted implementation uses start and stop as given and ignores score_ascending.
Source code in Modeling_Tool/Eval/evaluate_model.py
2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 | |
Weighted Implementations: weighted_eval_utils¶
Internal helpers behind the weighted path. The public functions above delegate to this module when they receive a weight argument. They are not exported and their signatures can change without notice.
weighted_eval_utils
¶
Native weighted evaluation helpers.
Shared implementation for public Eval APIs when sample_weight or
weight_col is supplied. Unweighted callers keep using the historical
implementations in evaluate_model.py and Model_Eval_Tool.py.
GainsTableCalculator
¶
Gains-table calculator bound to one dataset.
Stores the arguments of get_gains_table and computes the table with calculate.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame or None
|
Dataset that holds the target, the score and, when given, the weight column. It must be set before |
None
|
dep
|
str or None
|
Name of the target column (binary, 1 for bad). |
None
|
score
|
str or None
|
Name of the score column. |
None
|
nbins
|
int
|
Number of bins. |
10
|
weight_col
|
str or None
|
Name of the sample weight column in |
None
|
weighted_binning
|
bool or None
|
Accepted for compatibility but without any effect: the bins are always equal-weight bins. |
None
|
**kwargs
|
Extra keyword arguments of |
{}
|
Attributes:
| Name | Type | Description |
|---|---|---|
data, dep, score, nbins, weight_col, weighted_binning |
object
|
The constructor arguments, as given. |
kwargs |
dict
|
The extra keyword arguments. |
Source code in Modeling_Tool/Eval/weighted_eval_utils.py
calculate
¶
Compute the Gains table of the stored dataset with get_gains_table.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
weight_col
|
str or None
|
Weight column for this call; None keeps the |
None
|
**kwargs
|
Extra keyword arguments of |
{}
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
The Gains table (see |
Raises:
| Type | Description |
|---|---|
KeyError
|
If the target, score or weight column is not a column of |
ValueError
|
If the weights are invalid (see |
Source code in Modeling_Tool/Eval/weighted_eval_utils.py
PerformanceEvaluator
¶
Collect named datasets and summarize their performance with dataset_summary.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tgt_name
|
str or None
|
Name of the target column (binary, 1 for bad) in every dataset. |
None
|
scr_name
|
str or None
|
Name of the score column in every dataset. |
None
|
weight_col
|
str or None
|
Default sample weight column, used for the datasets added without one. |
None
|
nbins
|
int
|
Number of bins of the Gains table behind |
10
|
**kwargs
|
Stored in |
{}
|
Attributes:
| Name | Type | Description |
|---|---|---|
tgt_name, scr_name, weight_col, nbins |
object
|
The constructor arguments, as given. |
kwargs |
dict
|
The extra keyword arguments. |
datasets |
OrderedDict
|
Added datasets in insertion order: name mapped to the tuple |
Source code in Modeling_Tool/Eval/weighted_eval_utils.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 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 | |
add_dataset
¶
Register a dataset to be summarized by evaluate.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Label of the dataset. Adding a name that already exists replaces that dataset and keeps its position. |
required |
data
|
DataFrame
|
Dataset that holds the target and score columns (and the weight column, when used). |
required |
weight_col
|
str or None
|
Sample weight column of this dataset; None falls back to the |
None
|
**kwargs
|
Accepted and ignored. |
{}
|
Returns:
| Type | Description |
|---|---|
PerformanceEvaluator
|
The evaluator itself, so that calls can be chained. |
Source code in Modeling_Tool/Eval/weighted_eval_utils.py
evaluate
¶
Summarize every added dataset.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
weight_col
|
str or None
|
Weight column for the datasets added without their own; None falls back to the |
None
|
to_show
|
bool
|
Accepted for API compatibility; it has no effect. |
False
|
display
|
bool
|
Accepted for API compatibility; it has no effect. |
False
|
**kwargs
|
Accepted and ignored. |
{}
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
One row per added dataset, in insertion order, with the entries of |
Raises:
| Type | Description |
|---|---|
KeyError
|
If a target, score or weight column is missing from a dataset. |
ValueError
|
If the weights of a dataset are invalid (see |
Notes
The Gains table behind LIFT and IV uses nbins of the constructor, ascending=False and no special
score values.
Source code in Modeling_Tool/Eval/weighted_eval_utils.py
resolve_weights
¶
resolve_weights(data=None, weight_col=None, sample_weight=None, expected_len=None, wgt=None, wgt_col=None)
Resolve sample weights from a DataFrame column or an array.
Thin wrapper around Modeling_Tool.Core.sample_weight_utils.resolve_sample_weight that first maps the aliases
wgt_col to weight_col and wgt to sample_weight.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame or None
|
Frame that holds the weight column; required when |
None
|
weight_col
|
str or None
|
Name of the weight column in |
None
|
sample_weight
|
array - like or None
|
Weights given directly, one per row. It cannot be combined with |
None
|
expected_len
|
int or None
|
Required length of the weight vector; None skips the length check. |
None
|
wgt
|
array - like or None
|
Alias of |
None
|
wgt_col
|
str or None
|
Alias of |
None
|
Returns:
| Type | Description |
|---|---|
ndarray or None
|
The validated 1-D float weight vector, or None when neither a column nor an array was given. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If both a column and an array are given, if a column is given without |
KeyError
|
If the weight column is not in |
Source code in Modeling_Tool/Eval/weighted_eval_utils.py
safe_weighted_average
¶
Weighted mean that returns NaN instead of failing on empty or zero-weight input.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
values
|
array - like
|
Values to average, converted with |
required |
weights
|
array - like or None
|
Weights aligned with |
None
|
Returns:
| Type | Description |
|---|---|
float
|
The weighted mean. NaN when |
Notes
The weights are not validated: negative weights are used as given, and a weights array whose length differs from
values makes numpy.average raise TypeError.
Source code in Modeling_Tool/Eval/weighted_eval_utils.py
safe_auc
¶
Area under the ROC curve, or NaN when it cannot be computed.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
y_true
|
array - like
|
Actual binary labels (0/1). |
required |
y_score
|
array - like
|
Predicted scores or probabilities. |
required |
sample_weight
|
array - like or None
|
Per-sample weights passed to |
None
|
Returns:
| Type | Description |
|---|---|
float
|
The (weighted) AUC. NaN when scikit-learn raises |
Source code in Modeling_Tool/Eval/weighted_eval_utils.py
calc_roc
¶
Compute the statistics of the ROC curve, optionally with sample weights.
Based on sklearn.metrics.roc_curve. The rows where y_true, y_score or sample_weight is NaN or infinite
are dropped first.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
y_true
|
array - like
|
Actual binary labels (0/1), converted to float. |
required |
y_score
|
array - like
|
Predicted scores or probabilities, converted to float. |
required |
sample_weight
|
array - like or None
|
Per-sample weights aligned with |
None
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
One row per ROC threshold with the columns |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in Modeling_Tool/Eval/weighted_eval_utils.py
calc_pr
¶
Compute the statistics of the P-R curve, optionally with sample weights.
Based on sklearn.metrics.precision_recall_curve.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
y_true
|
array - like
|
Actual binary labels (0/1). |
required |
y_score
|
array - like
|
Predicted scores or probabilities. |
required |
sample_weight
|
array - like or None
|
Per-sample weights aligned with |
None
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
One row per threshold with the columns |
Notes
NaN or infinite values are not filtered out here, so scikit-learn raises ValueError when y_true or y_score
contains them.
Source code in Modeling_Tool/Eval/weighted_eval_utils.py
rank_bins
¶
Weighted equal-frequency rank bins.
ascending=False (default, legacy) sorts scores descending — bin 1 is
the highest-score bucket. ascending=True sorts scores ascending so
bin 1 is the lowest-score bucket, matching the unweighted
gains_ascending=True convention.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
score
|
array - like
|
Scores, converted to float. A NaN score is ranked after every finite score, whatever |
required |
weight
|
array - like or None
|
Weights aligned with |
required |
nbins
|
int
|
Number of bins (converted with |
required |
ascending
|
bool
|
False ranks the highest score first (bin 1 holds the highest scores); True ranks the lowest score first. |
False
|
Returns:
| Type | Description |
|---|---|
ndarray
|
Integer bin labels from 1 to |
Notes
Rows with the same score are ordered by their position in the input, so they can be split across two adjacent bins.
Source code in Modeling_Tool/Eval/weighted_eval_utils.py
get_gains_table
¶
get_gains_table(data, dep, score, nbins=10, weight_col=None, weighted_binning=None, ascending=False, spec_values=None, include_missing=False, add_func=None, withSummary=False, **kwargs)
Sample-weight-aware Gains table: equal-weight score bins with their target statistics.
The rows are ranked by score (see rank_bins) and cut into nbins bins that each hold about 1 / nbins of the
total weight. data is not modified.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame
|
Dataset that holds the target, the score and, when given, the weight column. |
required |
dep
|
str
|
Name of the target column; numeric, 1 for bad and 0 for good. |
required |
score
|
str
|
Name of the score column; converted to float. |
required |
nbins
|
int
|
Number of bins. |
10
|
weight_col
|
str or None
|
Name of the sample weight column in |
None
|
weighted_binning
|
bool or None
|
Accepted for compatibility but without any effect: the bins are always equal-weight bins. |
None
|
ascending
|
bool
|
False puts the highest scores in bin 1; True puts the lowest scores in bin 1. |
False
|
spec_values
|
list or None
|
Special score values (business sentinels such as |
None
|
include_missing
|
bool
|
Rows whose score is missing never enter the bins. False leaves them out of the table; True reports them in a row of their own (see Notes). |
False
|
add_func
|
callable or None
|
Custom statistics function, as in the unweighted table. It receives the rows of one row of the table as a
DataFrame (all the columns of |
None
|
withSummary
|
bool
|
Whether to add a |
False
|
**kwargs
|
Accepted and ignored. |
{}
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
One row per bin, indexed by
|
Raises:
| Type | Description |
|---|---|
KeyError
|
If |
ValueError
|
If the weights contain NaN, infinity or a negative value, or sum to zero or less. |
Notes
The statistics are computed on the rows that do not hold a special score. Each special score value gets one more row
after the bins, indexed by "special:<value>" in both index levels (in ascending order of the value), with the
columns MIN, MAX (both the value), N, N_RAW, PERF_CNT, N_BAD, N_GOOD, AVG_SCORE,
UNIQUE_SCORE (1), PROP, AVG_BAD, AVG_GOOD and AUC (the AUC of the regular rows); every other column
is NaN. PROP is the share of the weight of all rows in the regular bins and in the special rows alike, so the
column adds up to 1. The other shares (BAD_PCT_IN_EACH_BIN and GOOD_PCT_IN_EACH_BIN), LIFT and the overall
bad rate still refer to the rows without a special score.
Rows with a missing score carry no ranking information and never enter the bins. With include_missing=True they
get one row after the bins (and after the special rows), indexed by "Missing" in both index levels, with N,
N_RAW, PERF_CNT, N_BAD, N_GOOD, UNIQUE_SCORE (0), PROP, AVG_BAD, AVG_GOOD and AUC;
every other column is NaN. Rows with the same score can be split across two adjacent bins.
Source code in Modeling_Tool/Eval/weighted_eval_utils.py
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 | |
calc_lift_apt
¶
Closest available Lift values for a grid of target Lifts, from a weighted 100-bin Gains table.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
y_true
|
array - like
|
Actual binary labels (0/1), converted to float. |
required |
y_score
|
array - like
|
Predicted scores or probabilities, converted to float. |
required |
start
|
float
|
First target Lift. |
1.0
|
stop
|
float
|
Last target Lift (included up to rounding of the grid). |
3.0
|
step
|
float
|
Distance between two target Lifts. |
0.1
|
sample_weight
|
array - like or None
|
Per-sample weights aligned with |
None
|
Returns:
| Type | Description |
|---|---|
ndarray
|
One-dimensional float array with one value per target Lift of |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the weights are invalid (see |
Source code in Modeling_Tool/Eval/weighted_eval_utils.py
calc_equid_dist
¶
Weighted Gains table over bins equal-weight score bins.
Despite its name the bins are not equal-width: the weighted implementation cuts the ranked scores into bins that each
hold about 1 / bins of the total weight. It is the weighted counterpart of evaluate_model.calc_equid_dist.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
y_true
|
array - like
|
Actual binary labels (0/1). |
required |
y_score
|
array - like
|
Predicted scores or probabilities, same length as |
required |
bins
|
int
|
Number of bins. |
10
|
sample_weight
|
array - like or None
|
Per-sample weights aligned with |
None
|
**kwargs
|
Forwarded to |
{}
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
The Gains table of |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the weights are invalid (see |
Source code in Modeling_Tool/Eval/weighted_eval_utils.py
calc_equid_pct
¶
Weighted Gains table over bins equal-weight score bins.
Same as calc_equid_dist, to which it delegates: the weighted counterpart of evaluate_model.calc_equid_pct.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
y_true
|
array - like
|
Actual binary labels (0/1). |
required |
y_score
|
array - like
|
Predicted scores or probabilities, same length as |
required |
bins
|
int
|
Number of bins. |
10
|
sample_weight
|
array - like or None
|
Per-sample weights aligned with |
None
|
**kwargs
|
Forwarded to |
{}
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
The Gains table of |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the weights are invalid (see |
Source code in Modeling_Tool/Eval/weighted_eval_utils.py
calc_fixed_pct
¶
Weighted Gains table over equal-weight score bins; the weighted counterpart of evaluate_model.calc_fixed_pct.
Fixed bin edges are not supported here: the call delegates to calc_equid_dist, so the table has 10 equal-weight
bins unless bins is passed in kwargs.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
y_true
|
array - like
|
Actual binary labels (0/1). |
required |
y_score
|
array - like
|
Predicted scores or probabilities, same length as |
required |
sample_weight
|
array - like or None
|
Per-sample weights aligned with |
None
|
**kwargs
|
Forwarded to |
{}
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
The Gains table of |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the weights are invalid (see |
Source code in Modeling_Tool/Eval/weighted_eval_utils.py
dataset_summary
¶
dataset_summary(name, data, tgt_name, scr_name, weight_col=None, nbins=10, ascending=False, spec_values=None)
Performance summary of one dataset: AUC, KS, Lift, IV and the average target and score.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Label of the dataset; stored in the |
required |
data
|
DataFrame
|
Dataset that holds the target, the score and, when given, the weight column. |
required |
tgt_name
|
str
|
Name of the target column (binary, 1 for bad). |
required |
scr_name
|
str
|
Name of the score column. |
required |
weight_col
|
str or None
|
Name of the sample weight column in |
None
|
nbins
|
int
|
Number of bins of the Gains table behind |
10
|
ascending
|
bool
|
Bin order of that Gains table (see |
False
|
spec_values
|
list or None
|
Special score values (such as |
None
|
Returns:
| Type | Description |
|---|---|
dict
|
The entries |
Raises:
| Type | Description |
|---|---|
KeyError
|
If |
ValueError
|
If the weights contain NaN, infinity or a negative value, or sum to zero or less. |
Notes
AUC, KS, LIFT, IV and avgScore use the non-special rows only, because sentinel scores carry no
ordering information; avgTrue, N and N_RAW cover all rows. AUC and KS are NaN when they cannot be
computed (for example with a single class).
Source code in Modeling_Tool/Eval/weighted_eval_utils.py
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 | |
get_perf_summary
¶
get_perf_summary(train=None, validation=None, oot=None, tgt_name=None, scr_name=None, weight_col=None, nbins=10, ascending=False, spec_values=None, **kwargs)
Performance summary of the train, validation and OOT datasets, one row each.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
train
|
DataFrame or None
|
Training dataset, reported in the row |
None
|
validation
|
DataFrame or None
|
Validation dataset, reported in the row |
None
|
oot
|
DataFrame or None
|
Out-of-time dataset, reported in the row |
None
|
tgt_name
|
str or None
|
Name of the target column (binary, 1 for bad); required as soon as a dataset is given. |
None
|
scr_name
|
str or None
|
Name of the score column; required as soon as a dataset is given. |
None
|
weight_col
|
str or None
|
Name of the sample weight column, which must exist in every given dataset; None gives every row the weight 1. |
None
|
nbins
|
int
|
Number of bins of the Gains table behind |
10
|
ascending
|
bool
|
Bin order of that Gains table (see |
False
|
spec_values
|
list or None
|
Special score values (such as |
None
|
**kwargs
|
Accepted and ignored. |
{}
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
One row per given dataset, in the order |
Raises:
| Type | Description |
|---|---|
KeyError
|
If a target, score or weight column is missing from a given dataset. |
ValueError
|
If the weights are invalid (see |
Source code in Modeling_Tool/Eval/weighted_eval_utils.py
evaluate_performance
¶
evaluate_performance(datasets=None, tgt_name=None, scr_name=None, sample_weight=None, nbins=10, **kwargs)
Performance summary of several named datasets given as DataFrames or as label/score arrays.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
datasets
|
dict or None
|
Mapping of dataset name to a payload dict. A payload is either |
None
|
tgt_name
|
str or None
|
Name of the target column (binary, 1 for bad); for array payloads, the name given to the target column of the frame built from them. |
None
|
scr_name
|
str or None
|
Name of the score column; for array payloads, the name given to the score column of the frame built from them. |
None
|
sample_weight
|
array - like or None
|
Default weights, one per row, for the datasets whose payload has no |
None
|
nbins
|
int
|
Number of bins of the Gains table behind |
10
|
**kwargs
|
Accepted and ignored. |
{}
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
One row per dataset, in the order of |
Raises:
| Type | Description |
|---|---|
KeyError
|
If an array payload lacks |
ValueError
|
If the weights are invalid: wrong length, NaN, infinity, negative values or a sum that is not positive. |
Notes
Each frame is copied and given the weight column _w (overwriting any column of that name). ascending and
spec_values are not available here: the Gains table behind LIFT and IV uses ascending=False and no
special values.
Source code in Modeling_Tool/Eval/weighted_eval_utils.py
cross_risk_weighted_mean
¶
Weighted-mean cross-risk table after bin columns are assigned.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
DataFrame
|
Dataset that already holds the bin columns |
required |
agg_col
|
str
|
Name of the column to average (for example the target or a risk measure); converted with
|
required |
sample_weight
|
array - like
|
Weights, one per row of |
required |
score_list
|
list of str
|
Names of the two scores, |
required |
margin_name
|
str
|
Label of the margin row and column, which hold the weighted means over a whole row, a whole column and the whole table. |
"Total_Avg_Risk"
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
For every cell, the sum of |
Notes
A row whose agg_col value is NaN is skipped: it adds nothing to the numerator and its weight is left out of the
denominator, so the result is the weighted mean of the values that exist.