API Reference
Class APIs
The Sklearn Class Wrappers
TargetPermutationImportancesWrapper
TargetPermutationImportancesWrapper(
model_cls: Any,
model_cls_params: Dict,
num_actual_runs: PositiveInt = 2,
num_random_runs: PositiveInt = 10,
shuffle_feature_order: bool = False,
permutation_importance_calculator: PermutationImportanceCalculatorType = compute_permutation_importance_by_subtraction,
)
Compute the permutation importance of a model given a dataset.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
model_cls |
Any
|
The constructor/class of the model. |
required |
model_cls_params |
Dict
|
The parameters to pass to the model constructor. |
required |
model_fit_params |
The parameters to pass to the model fit method. |
required | |
num_actual_runs |
PositiveInt
|
Number of actual runs. Defaults to 2. |
2
|
num_random_runs |
PositiveInt
|
Number of random runs. Defaults to 10. |
10
|
shuffle_feature_order |
bool
|
Whether to shuffle the feature order for each run (only for X being pd.DataFrame). Defaults to False. |
False
|
permutation_importance_calculator |
PermutationImportanceCalculatorType
|
The function to compute the final importance. Defaults to compute_permutation_importance_by_subtraction. |
compute_permutation_importance_by_subtraction
|
Example
# Import the package
import target_permutation_importances as tpi
# Prepare a dataset
import pandas as pd
import numpy as np
from sklearn.datasets import load_breast_cancer
# Models
from sklearn.feature_selection import SelectFromModel
from sklearn.ensemble import RandomForestClassifier
data = load_breast_cancer()
# Convert to a pandas dataframe
Xpd = pd.DataFrame(data.data, columns=data.feature_names)
# Compute permutation importances with default settings
wrapped_model = tpi.TargetPermutationImportancesWrapper(
model_cls=RandomForestClassifier, # The constructor/class of the model.
model_cls_params={ # The parameters to pass to the model constructor. Update this based on your needs.
"n_jobs": -1,
},
num_actual_runs=2,
num_random_runs=10,
# Options: {compute_permutation_importance_by_subtraction, compute_permutation_importance_by_division}
# Or use your own function to calculate.
permutation_importance_calculator=tpi.compute_permutation_importance_by_subtraction,
)
wrapped_model.fit(
X=Xpd, # pd.DataFrame, np.ndarray
y=data.target, # pd.Series, np.ndarray
# And other fit parameters for the model.
)
# Get the feature importances as a pandas dataframe
result_df = wrapped_model.feature_importances_df
print(result_df[["feature", "importance"]].sort_values("importance", ascending=False).head())
# Select top-5 features with sklearn `SelectFromModel`
selector = SelectFromModel(
estimator=wrapped_model, prefit=True, max_features=5, threshold=-np.inf
).fit(Xpd, data.target)
selected_x = selector.transform(Xpd)
print(selected_x.shape)
print(selector.get_feature_names_out())
Source code in target_permutation_importances/sklearn_wrapper.py
fit
Compute the permutation importance of a model given a dataset.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
X |
XType
|
The input data. |
required |
y |
YType
|
The target vector. |
required |
fit_params |
The parameters to pass to the model fit method. |
{}
|
Source code in target_permutation_importances/sklearn_wrapper.py
Functional APIs
The core APIs of this library.
compute
compute(
model_cls: Any,
model_cls_params: Dict,
model_fit_params: Union[
ModelFitParamsBuilderType, Dict
],
X: XType,
y: YType,
num_actual_runs: PositiveInt = 2,
num_random_runs: PositiveInt = 10,
shuffle_feature_order: bool = False,
permutation_importance_calculator: Union[
PermutationImportanceCalculatorType,
List[PermutationImportanceCalculatorType],
] = compute_permutation_importance_by_subtraction,
) -> Union[pd.DataFrame, List[pd.DataFrame]]
Compute the permutation importance of a model given a dataset.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
model_cls |
Any
|
The constructor/class of the model. |
required |
model_cls_params |
Dict
|
The parameters to pass to the model constructor. |
required |
model_fit_params |
Union[ModelFitParamsBuilderType, Dict]
|
A Dict or A function that return parameters to pass to the model fit method. |
required |
X |
XType
|
The input data. |
required |
y |
YType
|
The target vector. |
required |
num_actual_runs |
PositiveInt
|
Number of actual runs. Defaults to 2. |
2
|
num_random_runs |
PositiveInt
|
Number of random runs. Defaults to 10. |
10
|
shuffle_feature_order |
bool
|
Whether to shuffle the feature order for each run (only for X being pd.DataFrame). Defaults to False. |
False
|
permutation_importance_calculator |
Union[PermutationImportanceCalculatorType, List[PermutationImportanceCalculatorType]]
|
The function to compute the final importance. Defaults to compute_permutation_importance_by_subtraction. |
compute_permutation_importance_by_subtraction
|
Returns:
Type | Description |
---|---|
Union[DataFrame, List[DataFrame]]
|
The return DataFrame(s) contain columns ["feature", "importance"] |
Example
# import the package
import target_permutation_importances as tpi
# Prepare a dataset
import pandas as pd
from sklearn.datasets import load_breast_cancer
# Models
from sklearn.ensemble import RandomForestClassifier
data = load_breast_cancer()
# Convert to a pandas dataframe
Xpd = pd.DataFrame(data.data, columns=data.feature_names)
# Compute permutation importances with default settings
result_df = tpi.compute(
model_cls=RandomForestClassifier, # The constructor/class of the model.
model_cls_params={ # The parameters to pass to the model constructor. Update this based on your needs.
"n_jobs": -1,
},
model_fit_params={}, # The parameters to pass to the model fit method. Update this based on your needs.
X=Xpd, # pd.DataFrame, np.ndarray
y=data.target, # pd.Series, np.ndarray
num_actual_runs=2,
num_random_runs=10,
# Options: {compute_permutation_importance_by_subtraction, compute_permutation_importance_by_division}
# Or use your own function to calculate.
permutation_importance_calculator=tpi.compute_permutation_importance_by_subtraction,
)
print(result_df[["feature", "importance"]].sort_values("importance", ascending=False).head())
Source code in target_permutation_importances/functional.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 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 |
|
generic_compute
generic_compute(
model_builder: ModelBuilderType,
model_fitter: ModelFitterType,
importance_getter: ModelImportanceGetter,
permutation_importance_calculator: Union[
PermutationImportanceCalculatorType,
List[PermutationImportanceCalculatorType],
],
X_builder: XBuilderType,
y_builder: YBuilderType,
num_actual_runs: PositiveInt = 2,
num_random_runs: PositiveInt = 10,
) -> Union[pd.DataFrame, List[pd.DataFrame]]
The generic compute function allows customization of the computation. It is used by the compute
function.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
model_builder |
ModelBuilderType
|
A function that return a model. |
required |
model_fitter |
ModelFitterType
|
A function that fit a model. |
required |
importance_getter |
ModelImportanceGetter
|
A function that compute the importance of a model. |
required |
permutation_importance_calculator |
Union[PermutationImportanceCalculatorType, List[PermutationImportanceCalculatorType]]
|
A function or list of functions that compute the final permutation importance. |
required |
X_builder |
XBuilderType
|
A function that return the X data. |
required |
y_builder |
YBuilderType
|
A function that return the y data. |
required |
num_actual_runs |
PositiveInt
|
Number of actual runs. Defaults to 2. |
2
|
num_random_runs |
PositiveInt
|
Number of random runs. Defaults to 10. |
10
|
Returns:
Type | Description |
---|---|
Union[DataFrame, List[DataFrame]]
|
The return DataFrame(s) contain columns ["feature", "importance"] |
Source code in target_permutation_importances/functional.py
Type Definitions
XBuilderType
YBuilderType
ModelBuilderType
ModelFitterType
ModelImportanceGetter
A function/callable computes the feature importances of a fitted model. This function is called once per run (actual and random)
Parameters:
Name | Type | Description | Default |
---|---|---|---|
model |
Any
|
The fitted model |
required |
X |
XType
|
The X data |
required |
y |
YType
|
The y data |
required |
Returns: return (pd.DataFrame): The return DataFrame with columns ["feature", "importance"]
PermutationImportanceCalculatorType
A function/callable that takes in a list of actual importance DataFrames and a list of random importance s and returns a single DataFrame
Parameters:
Name | Type | Description | Default |
---|---|---|---|
actual_importance_dfs |
List[DataFrame]
|
list of actual importance DataFrames with columns ["feature", "importance"] |
required |
random_importance_dfs |
List[DataFrame]
|
list of random importance DataFrames with columns ["feature", "importance"] |
required |
Returns:
Name | Type | Description |
---|---|---|
return |
DataFrame
|
The return DataFrame with columns ["feature", "importance"] |