Modeling_Tool.Sample¶
Sample management layer: splitting, stratified sampling, class balancing, reject inference, and distribution adaptation. User guides: Sample Management and Reject Inference and Distribution Adaptation.
Splitting and Sampling: Sample_Split¶
Sample_Split
¶
Sampling classes for credit modeling.
This module provides classes for splitting samples, stratified sampling, and sample balancing for credit model development.
Classes:
| Name | Description |
|---|---|
SampleSplitter : Split data into train/test samples. |
|
StratifiedSampler : Stratified sampling with target balance control. |
|
SampleBalancer : Balance samples using various techniques. |
|
Examples:
>>> from Modeling_Tool_refactored.sample import SampleSplitter
>>> splitter = SampleSplitter()
>>> train, test = splitter.split(df, 'target', test_size=0.3)
SampleSplitter
¶
Split data into training and testing samples.
This class provides flexible sample splitting with support for stratification, random sampling, and custom split ratios.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
test_size
|
float
|
Proportion of data for testing (0 to 1). |
0.3
|
random_state
|
int
|
Random seed for reproducibility. |
None
|
stratify
|
bool
|
Whether to stratify by target variable. |
True
|
Attributes:
| Name | Type | Description |
|---|---|---|
train_index_ |
ndarray
|
Indices for training data. |
test_index_ |
ndarray
|
Indices for testing data. |
Methods:
| Name | Description |
|---|---|
split |
Split data into train and test sets. |
split_df |
Split DataFrame while excluding certain columns. |
Examples:
>>> splitter = SampleSplitter(test_size=0.2, random_state=42)
>>> train, test = splitter.split(X, y)
>>> print(f"Train size: {len(train)}, Test size: {len(test)}")
Source code in Modeling_Tool/Sample/Sample_Split.py
110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 | |
split
¶
split(X: Union[DataFrame, ndarray], y: Union[Series, ndarray], test_size: Optional[float] = None, stratify: Optional[bool] = None) -> Tuple
Split data into train and test sets.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X
|
DataFrame or ndarray
|
Features. |
required |
y
|
Series or ndarray
|
Target variable. |
required |
test_size
|
float
|
Override default test size. |
None
|
stratify
|
bool
|
Override default stratify setting. |
None
|
Returns:
| Type | Description |
|---|---|
tuple
|
(X_train, X_test, y_train, y_test) |
Examples:
Source code in Modeling_Tool/Sample/Sample_Split.py
split_indices
¶
split_indices(index: Union[Index, ndarray, List[Any]], y: Union[Series, ndarray], test_size: Optional[float] = None, stratify: Optional[bool] = None) -> Tuple[ndarray, ndarray]
Split index labels without copying the underlying feature frame.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
index
|
(Index, ndarray or list)
|
Row labels (or positions) to split. |
required |
y
|
Series or ndarray
|
Target values, one per label, used for stratification. |
required |
test_size
|
float or None
|
Share of the labels that goes to the test side; None uses the |
None
|
stratify
|
bool or None
|
Whether to stratify by |
None
|
Returns:
| Type | Description |
|---|---|
tuple of numpy.ndarray
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in Modeling_Tool/Sample/Sample_Split.py
split_df
¶
split_df(df: DataFrame, target: str, exclude_cols: Optional[List[str]] = None, test_size: Optional[float] = None) -> Tuple[DataFrame, DataFrame]
Split DataFrame into train/test partitions while keeping every column.
exclude_cols means "these columns should not participate in the
split strategy" (i.e. they must not be used as stratify keys or as
features driving the split), not "these columns should be dropped
from the output frames." Before 0.4.2 the columns listed here were
silently dropped from train_df / test_df, which broke every
downstream step that relied on carry-through keys such as user_id
or apply_date. Fixed in 0.4.2: both output frames now contain the
full column set of the input frame.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DataFrame
|
Input DataFrame. |
required |
target
|
str
|
Target column name. |
required |
exclude_cols
|
list of str
|
Columns to carry through the split without letting them influence the split strategy. Their values are preserved verbatim on both output frames. |
None
|
test_size
|
float
|
Override default test size. |
None
|
Returns:
| Type | Description |
|---|---|
tuple
|
(train_df, test_df) — both include every column of |
Examples:
>>> train_df, test_df = splitter.split_df(df, 'target', exclude_cols=['id', 'date'])
>>> assert 'id' in train_df.columns and 'date' in test_df.columns
Source code in Modeling_Tool/Sample/Sample_Split.py
StratifiedSampler
¶
Stratified sampling with target balance control.
This class provides stratified sampling that maintains the target distribution while allowing controlled sampling.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
target_rate
|
float
|
Target bad rate in the sample. |
None
|
random_state
|
int
|
Random seed. |
None
|
Methods:
| Name | Description |
|---|---|
sample |
Perform stratified sampling. |
balance |
Balance sample by adjusting target distribution. |
Examples:
>>> sampler = StratifiedSampler(target_rate=0.15)
>>> balanced = sampler.balance(df, 'target', method='undersample')
Source code in Modeling_Tool/Sample/Sample_Split.py
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 | |
sample
¶
sample(df: DataFrame, target: str, n_samples: Optional[int] = None, sample_frac: Optional[float] = None) -> DataFrame
Perform stratified sampling.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DataFrame
|
Input data. |
required |
target
|
str
|
Target column name. |
required |
n_samples
|
int
|
Number of samples to draw. |
None
|
sample_frac
|
float
|
Fraction of data to sample. |
None
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
Sampled DataFrame. |
Examples:
Source code in Modeling_Tool/Sample/Sample_Split.py
balance
¶
Balance sample by adjusting target distribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DataFrame
|
Input data. |
required |
target
|
str
|
Target column name. |
required |
method
|
str
|
Balancing method: 'undersample', 'oversample', 'smote'. |
'undersample'
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
Balanced DataFrame. |
Examples:
Source code in Modeling_Tool/Sample/Sample_Split.py
SampleBalancer
¶
Advanced sample balancing with multiple methods.
This class provides various sampling techniques to handle class imbalance in credit modeling.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
method
|
str
|
Balancing method. |
'random'
|
target_ratio
|
float
|
Desired minority/majority ratio. |
None
|
random_state
|
int
|
Random seed. |
None
|
Methods:
| Name | Description |
|---|---|
fit_resample |
Resample features and target. |
get_balanced_indices |
Get indices for balanced sampling. |
Examples:
Source code in Modeling_Tool/Sample/Sample_Split.py
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 | |
fit_resample
¶
Resample data to balance classes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X
|
DataFrame or ndarray
|
Features. |
required |
y
|
Series or ndarray
|
Target. |
required |
Returns:
| Type | Description |
|---|---|
tuple
|
(X_resampled, y_resampled) |
Examples:
Source code in Modeling_Tool/Sample/Sample_Split.py
select_sample_seed
¶
select_sample_seed(master_df, oot_split_col, model, tgt_name, seed_range=(3000, 3050), ins_prop=0.7)
Compare model performance across INS/OOS splits made with different seeds, to help choose a seed.
For every seed in range(seed_range[0], seed_range[1]) the rows with oot_split_col == 1 are split into INS
and OOS (stratified by tgt_name), the rows with oot_split_col == 2 are the OOT sample, and a
PerformanceEvaluator summarizes the model on the three samples.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
master_df
|
DataFrame
|
Full modeling population with the target, the split column and the features (or the score column). |
required |
oot_split_col
|
str
|
Column that marks the modeling sample (value 1) and the OOT sample (value 2). |
required |
model
|
object or str
|
A fitted model whose feature names can be read, or the name of a score column that already exists in
|
required |
tgt_name
|
str
|
Name of the binary target column. |
required |
seed_range
|
tuple of int
|
|
(3000, 3050)
|
ins_prop
|
float
|
Share of the modeling sample that goes to INS; the rest is OOS. |
0.7
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
The performance summaries of all seeds stacked on top of each other, with a |
Source code in Modeling_Tool/Sample/Sample_Split.py
Reject Inference: Reject_Infer¶
Reject_Infer
¶
Reject inference classes for credit modeling.
This module provides classes for applying reject inference techniques to handle the selection bias in credit modeling when using approved loan data only.
Classes:
| Name | Description |
|---|---|
RejectInferrer : Base class for reject inference. |
|
RejectInferenceFactory : Factory for creating reject inference methods. |
|
ParcelingInferrer : Parceling method for reject inference. |
|
FuzzyAugmentInferrer : Fuzzy augmentation method. |
|
HardCutoffInferrer : Hard cutoff method. |
|
SimpleAugmentInferrer : Simple augmentation method. |
|
Examples:
>>> from Modeling_Tool import RejectInferenceFactory
>>> inferrer = RejectInferenceFactory.create('parceling')
>>> df_inferred = inferrer.infer(df_approved, df_rejected, 'score')
RejectInferrer
¶
Bases: ABC
Abstract base class for reject inference methods.
Reject inference is used to address selection bias when building credit models on approved loans only.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
target_col
|
str
|
Name of the target column. |
'target'
|
score_col
|
str
|
Name of the score/probability column. |
'score'
|
score_direction
|
str
|
Meaning of the score, |
'high_good'
|
random_state
|
int or None
|
Seed of the numpy random generator used by the methods that draw random
labels ( |
None
|
Attributes:
| Name | Type | Description |
|---|---|---|
target_col |
str
|
Stored constructor argument. |
score_col |
str
|
Stored constructor argument. |
score_direction |
str
|
Stored constructor argument. |
random_state |
int or None
|
Stored constructor argument. |
Methods:
| Name | Description |
|---|---|
infer |
Apply reject inference. |
Source code in Modeling_Tool/Sample/Reject_Infer.py
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 | |
infer
abstractmethod
¶
Apply reject inference.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df_approved
|
DataFrame
|
DataFrame with approved applications (has target). |
required |
df_rejected
|
DataFrame
|
DataFrame with rejected applications (no target). |
required |
score_col
|
str
|
Score column name. If None, the |
None
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
Combined DataFrame with inferred targets for rejected applications. |
Source code in Modeling_Tool/Sample/Reject_Infer.py
SimpleAugmentInferrer
¶
Bases: RejectInferrer
Simple augmentation reject inference method.
Assigns the average bad rate from approved applications to all rejected applications.
Every rejected application receives an independent 0/1 label drawn with probability equal to that bad rate; scores are not used.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
target_col
|
str
|
Name of the target column. Its mean in |
'target'
|
score_col
|
str
|
Default score column name of |
'score'
|
bad_rate
|
float or None
|
Override bad rate to use. If None, the mean of |
None
|
score_direction
|
str
|
|
'high_good'
|
random_state
|
int or None
|
Seed of the random generator that draws the labels. |
None
|
Notes
Every constructor parameter is also stored as a public attribute of the same name.
Examples:
Source code in Modeling_Tool/Sample/Reject_Infer.py
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 | |
infer
¶
Apply simple augmentation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df_approved
|
DataFrame
|
Approved applications. Must contain the target column unless
|
required |
df_rejected
|
DataFrame
|
Rejected applications. |
required |
score_col
|
str
|
Score column. Not used by this method; accepted for interface compatibility. |
None
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
Combined data with inferred targets: the approved rows followed by the rejected rows (index reset), with the target column of the rejected rows overwritten by random 0/1 labels. The inputs are not modified. |
Source code in Modeling_Tool/Sample/Reject_Infer.py
HardCutoffInferrer
¶
Bases: RejectInferrer
Hard cutoff reject inference method.
Assigns all rejected applications below a score threshold as bad (target=1), and all above as good (target=0).
This is the rule for score_direction='high_good' (the default): a score
equal to the cutoff is labelled bad. With score_direction='high_bad' the
rule is reversed: scores at or above the cutoff are bad (target=1) and scores
below it are good (target=0). Only the scores of the rejected applications
are used.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
target_col
|
str
|
Name of the target column that receives the inferred labels of the rejected applications. |
'target'
|
score_col
|
str
|
Name of the score column of the rejected applications, used when |
'score'
|
cutoff
|
float
|
Score cutoff threshold, compared with the raw score (no rescaling). |
0.5
|
score_direction
|
str
|
|
'high_good'
|
random_state
|
int or None
|
Accepted for consistency with the other methods; this method draws no random numbers, so it has no effect. |
None
|
Notes
Every constructor parameter is also stored as a public attribute of the same name.
Examples:
>>> inferrer = HardCutoffInferrer(cutoff=0.3)
>>> df_combined = inferrer.infer(df_approved, df_rejected, 'probability')
Source code in Modeling_Tool/Sample/Reject_Infer.py
273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 | |
infer
¶
Apply hard cutoff inference.
NaN-scored rejects (0.4.2 fix, N17)
Before 0.4.2, any rejected row whose score_col value was NaN was
silently labelled 0 ("good") because NaN >= cutoff and
NaN <= cutoff both evaluate to False, which the old code then
cast through .astype(int). That silently seeded the training set
with as many synthetic "good" rejects as there were NaN scores, biasing
every downstream model that consumed the combined frame.
From 0.4.2:
- If every reject has a NaN score,
ValueErroris raised with the missing count — the caller has no signal to infer from and must re-check upstream scoring. - If some rejects have NaN scores, a
RuntimeWarningis emitted naming the NaN count and share, and those rows carrytarget = NaNin the returned frame (not0). Callers that intersect on the target column will drop them explicitly instead of training on silently-fabricated labels. - Rejects with finite scores are labelled exactly as before.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df_approved
|
DataFrame
|
Approved applications (concatenated unchanged; their scores and target are not read). |
required |
df_rejected
|
DataFrame
|
Rejected applications. |
required |
score_col
|
str
|
Score column of |
None
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
Combined data with inferred targets: the approved rows followed by the
rejected rows (index reset). The target of the rejected rows is a float
column holding 1.0 (bad), 0.0 (good) or NaN. Rejects whose score was NaN
(see above) will have |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in Modeling_Tool/Sample/Reject_Infer.py
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 | |
FuzzyAugmentInferrer
¶
Bases: RejectInferrer
Fuzzy augmentation reject inference method.
Weights approved applications based on their predicted probability and creates pseudo-target values for rejected applications.
Concretely, every rejected application is duplicated into a bad copy
(target 1, _weight = p_bad * weight_factor) and a good copy (target 0,
_weight = (1 - p_bad) * weight_factor), where p_bad is the bad
probability derived from the score (see score_direction). The approved
applications are kept with _weight = 1.0. The output therefore has an
extra _weight column, to be used as sample weights when training.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
target_col
|
str
|
Name of the target column that receives the inferred labels (1 and 0) of the rejected copies. |
'target'
|
score_col
|
str
|
Name of the score column of the rejected applications, used when |
'score'
|
weight_factor
|
float
|
Factor to adjust weights: it multiplies the |
1.0
|
score_direction
|
str
|
|
'high_good'
|
random_state
|
int or None
|
Accepted for consistency with the other methods; this method draws no random numbers, so it has no effect. |
None
|
nan_score_policy
|
str
|
How |
'drop'
|
Notes
Every constructor parameter is also stored as a public attribute of the same name.
Examples:
>>> inferrer = FuzzyAugmentInferrer(weight_factor=0.9)
>>> df_combined = inferrer.infer(df_approved, df_rejected, 'probability')
Source code in Modeling_Tool/Sample/Reject_Infer.py
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 | |
infer
¶
Apply fuzzy augmentation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df_approved
|
DataFrame
|
Approved applications (kept with |
required |
df_rejected
|
DataFrame
|
Rejected applications. |
required |
score_col
|
str
|
Score column of |
None
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
Combined data with inferred targets and a |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in Modeling_Tool/Sample/Reject_Infer.py
ParcelingInferrer
¶
Bases: RejectInferrer
Parceling reject inference method.
Splits rejected applications into parcels based on score bands and assigns average bad rate from approved applications in each parcel.
The parcels are quantile bins of the bad probability of the approved
applications (see score_direction). Every rejected application falls into
the parcel matching its own bad probability and receives a random 0/1 label
drawn with that parcel's approved bad rate; rejected rows that cannot be
assigned to a parcel (NaN score) use the overall approved bad rate.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
target_col
|
str
|
Name of the target column. Its mean per parcel in |
'target'
|
score_col
|
str
|
Name of the score column, which must exist in both |
'score'
|
n_parcels
|
int
|
Number of score parcels (quantile bins of the approved scores). Fewer parcels are created when the quantile edges are not unique, and a single parcel when the approved scores cannot be binned. |
10
|
score_direction
|
str
|
|
'high_good'
|
random_state
|
int or None
|
Seed of the random generator that draws the labels. |
None
|
Attributes:
| Name | Type | Description |
|---|---|---|
parcel_rates_ |
Series or None
|
Bad rate of the approved applications in each parcel, indexed by parcel
number. |
parcel_edges_ |
ndarray or None
|
Edges of the parcels in bad-probability space, with the first edge set to
|
Notes
Every constructor parameter is also stored as a public attribute of the same name.
Examples:
>>> inferrer = ParcelingInferrer(n_parcels=5)
>>> df_combined = inferrer.infer(df_approved, df_rejected, 'score')
Source code in Modeling_Tool/Sample/Reject_Infer.py
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 | |
infer
¶
Apply parceling inference.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df_approved
|
DataFrame
|
Approved applications; must contain the target column and the score column. |
required |
df_rejected
|
DataFrame
|
Rejected applications; must contain the score column. |
required |
score_col
|
str
|
Score column of both frames. If None, the |
None
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
Combined data with inferred targets: the approved rows followed by the
rejected rows (index reset), with the target column of the rejected rows
overwritten by random 0/1 labels. The inputs are not modified; the parcel
statistics are stored in |
Source code in Modeling_Tool/Sample/Reject_Infer.py
RejectInferenceFactory
¶
Factory class for creating reject inference methods.
Examples:
>>> inferrer = RejectInferenceFactory.create('parceling', n_parcels=5)
>>> inferrer = RejectInferenceFactory.create('fuzzy', weight_factor=0.9)
Source code in Modeling_Tool/Sample/Reject_Infer.py
create
classmethod
¶
create(method: str = 'parceling', **kwargs) -> RejectInferrer
Create a reject inference method.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
method
|
str
|
Method name, case-insensitive: |
'parceling'
|
**kwargs
|
Additional parameters for the method: keyword arguments passed to the
constructor of the selected class (for example |
{}
|
Returns:
| Type | Description |
|---|---|
RejectInferrer
|
Instantiated reject inferrer. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If method name is not recognized. |
Source code in Modeling_Tool/Sample/Reject_Infer.py
available_methods
classmethod
¶
Get list of available methods.
Returns:
| Type | Description |
|---|---|
list of str
|
Available method names: every name accepted by |
Source code in Modeling_Tool/Sample/Reject_Infer.py
Distribution Adaptation: Distribution_Adaptation¶
Distribution_Adaptation
¶
DistributionAdaptation
¶
Sample weights that adapt a training set to an out-of-time (OOT) distribution.
The class computes one importance weight per training row, so that the weighted
training distribution moves towards the OOT distribution. The weights are
produced either by fit (stored in sample_weights, read with get_weights) or
by calling estimate_density_ratio / covariate_shift_weighting directly.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
method
|
str
|
Weighting method used by
|
'density_ratio'
|
Attributes:
| Name | Type | Description |
|---|---|---|
method |
str
|
Weighting method passed to the constructor; only |
sample_weights |
ndarray or None
|
Weights computed by the last call to |
feature_importances |
None
|
Reserved attribute that is always |
Source code in Modeling_Tool/Sample/Distribution_Adaptation.py
9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 | |
estimate_density_ratio
¶
Compute sample weights using density-ratio estimation. A simplified implementation of methods such as KLIEP/KMM.
Two Gaussian kernel density estimates (bandwidth 0.5) are fitted, one on
X_train and one on X_oot. The weight of each training row is the ratio
p_oot(x) / p_train(x) evaluated at that row. The ratios are clipped to
[0.1, 10] and then divided by their mean.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X_train
|
array-like of shape (n_train, n_features)
|
Training features (numpy array or DataFrame), numeric without missing values. |
required |
X_oot
|
array-like of shape (n_oot, n_features)
|
OOT features with the same columns, in the same order, as |
required |
Returns:
| Type | Description |
|---|---|
numpy.ndarray of shape (n_train,)
|
Importance weight of each training row, in the row order of |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the inputs contain NaN or have a different number of columns (raised by scikit-learn). |
Notes
The kernel bandwidth is fixed at 0.5 and no feature scaling is applied, so the
features should be on comparable scales. The method does not read method
and does not store its result in sample_weights (fit does).
Source code in Modeling_Tool/Sample/Distribution_Adaptation.py
covariate_shift_weighting
¶
Estimate sample importance weights using a domain classifier.
A logistic regression (C=1.0, max_iter=1000, random_state=42) is
trained on the stacked rows of X_train (domain 0) and X_oot (domain 1).
The weight of each training row is the odds p(oot|x) / (1 - p(oot|x) + 1e-10)
predicted for that row. The odds are clipped to [0.1, 10] and then divided
by their mean.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X_train
|
array-like of shape (n_train, n_features)
|
Training features (numpy array or DataFrame), numeric without missing values. |
required |
X_oot
|
array-like of shape (n_oot, n_features)
|
OOT features with the same columns, in the same order, as |
required |
Returns:
| Type | Description |
|---|---|
numpy.ndarray of shape (n_train,)
|
Importance weight of each training row, in the row order of |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the inputs contain NaN or have a different number of columns (raised by numpy or scikit-learn). |
Notes
No feature scaling is applied and the odds are not corrected for the different
sizes of X_train and X_oot before clipping. The method does not read
method and does not store its result in sample_weights (fit does).
Source code in Modeling_Tool/Sample/Distribution_Adaptation.py
fit
¶
Compute sample weights that adapt the training distribution to the OOT distribution.
The weights are computed according to method and stored in
sample_weights: 'density_ratio' uses estimate_density_ratio,
'covariate_shift' uses covariate_shift_weighting, and any other value
uses the average of the two weight vectors.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X_train
|
array-like of shape (n_train, n_features)
|
Training features (numpy array or DataFrame), numeric without missing values. |
required |
X_oot
|
array-like of shape (n_oot, n_features)
|
OOT features with the same columns, in the same order, as |
required |
y_train
|
array - like or None
|
Not used; accepted only for interface compatibility. |
None
|
Returns:
| Type | Description |
|---|---|
DistributionAdaptation
|
The fitted instance itself ( |
Source code in Modeling_Tool/Sample/Distribution_Adaptation.py
get_weights
¶
Return the sample weights.
Returns:
| Type | Description |
|---|---|
ndarray or None
|
The weights stored by the last call to |
Source code in Modeling_Tool/Sample/Distribution_Adaptation.py
visualize_distribution_comparison
¶
Visualize the distribution differences between the training set and the OOT set.
Draws one filled kernel-density plot per feature (training set labelled
Train, OOT set labelled OOT) on a single row of n_features
subplots, then calls plt.tight_layout() and plt.show().
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X_train
|
numpy.ndarray of shape (n_train, n_total_features)
|
Training features. Must be a 2-D numpy array because columns are selected by position; a DataFrame raises an error. |
required |
X_oot
|
numpy.ndarray of shape (n_oot, n_total_features)
|
OOT features with the same column order as |
required |
features
|
sequence of int or None
|
Column positions (not names) to plot; only the first |
None
|
n_features
|
int
|
Number of subplots in the figure and maximum number of features plotted. |
5
|
Returns:
| Type | Description |
|---|---|
None
|
The figure is only displayed. |
Notes
The figure always has n_features subplots, so subplots are left empty when
fewer features are available. Each subplot is titled Feature <column position>.