RobustCSClassifier#

class empulse.models.RobustCSClassifier(estimator, outlier_estimator=None, *, outlier_threshold=2.5, detect_outliers_for='all', tp_cost=0.0, tn_cost=0.0, fn_cost=0.0, fp_cost=0.0)[source]#

Classifier that fits a cost-sensitive classifier with costs adjusted for outliers.

The costs are adjusted by fitting an outlier estimator to the costs and imputing the costs for the outliers. Outliers are detected by the standardized residuals of the cost and the predicted cost. The costs passed to the cost-sensitive classifier are a combination of the original costs (not non-outliers) and the imputed predicted costs (for outliers).

Read more in the User Guide.

Parameters:
estimatorEstimator

The cost-sensitive classifier to fit. The estimator must take tp_cost, tn_cost, fn_cost, and fp_cost as keyword arguments in its fit method.

outlier_estimatorEstimator, optional

The outlier estimator to fit to the costs.

If not provided, a sklearn.linear_model.HuberRegressor is used with default settings.

outlier_thresholdfloat, default=2.5

The threshold for the standardized residuals to detect outliers. If the absolute value of the standardized residual is greater than the threshold, the cost is an outlier and will be imputed with the predicted cost.

detect_outliers_for{‘all’, ‘tp_cost’, ‘tn_cost’, ‘fn_cost’, ‘fp_cost’, list}, default=’all’

The costs for which to detect outliers. By default, all instance-dependent costs are used for outlier detection. If a single cost is passed, only that cost is used for outlier detection. If a list of costs is passed, only those costs are used for outlier detection. tp_cost : float or array-like, shape=(n_samples,), default=0.0 Cost of true positives. If float, then all true positives have the same cost. If array-like, then it is the cost of each true positive classification. Is overwritten if another tp_cost is passed to the fit method.

Note

It is not recommended to pass instance-dependent costs to the __init__ method. Instead, pass them to the fit method.

tp_costfloat or array-like, shape=(n_samples,), default=0.0

Cost of true positives. If float, then all true positives have the same cost. If array-like, then it is the cost of each true positive classification. Is overwritten if another tp_cost is passed to the fit method.

Note

It is not recommended to pass instance-dependent costs to the __init__ method. Instead, pass them to the fit method.

fp_costfloat or array-like, shape=(n_samples,), default=0.0

Cost of false positives. If float, then all false positives have the same cost. If array-like, then it is the cost of each false positive classification. Is overwritten if another fp_cost is passed to the fit method.

Note

It is not recommended to pass instance-dependent costs to the __init__ method. Instead, pass them to the fit method.

tn_costfloat or array-like, shape=(n_samples,), default=0.0

Cost of true negatives. If float, then all true negatives have the same cost. If array-like, then it is the cost of each true negative classification. Is overwritten if another tn_cost is passed to the fit method.

Note

It is not recommended to pass instance-dependent costs to the __init__ method. Instead, pass them to the fit method.

fn_costfloat or array-like, shape=(n_samples,), default=0.0

Cost of false negatives. If float, then all false negatives have the same cost. If array-like, then it is the cost of each false negative classification. Is overwritten if another fn_cost is passed to the fit method.

Note

It is not recommended to pass instance-dependent costs to the __init__ method. Instead, pass them to the fit method.

Attributes:
estimator_Estimator

The fitted cost-sensitive classifier.

outlier_estimators_dict{str, Estimator or None}

The fitted outlier estimators. If no outliers are detected for this cost, the value is None. The keys of the directory are ‘tp_cost’, ‘tn_cost’, ‘fn_cost’, and ‘fp_cost’.

costs_dict

The imputed costs for the cost-sensitive classifier.

Notes

Constant costs are not used for outlier detection and imputation.

Code adapted from [1].

References

[1]

De Vos, S., Vanderschueren, T., Verdonck, T., & Verbeke, W. (2023). Robust instance-dependent cost-sensitive classification. Advances in Data Analysis and Classification, 17(4), 1057-1079.

Examples

import numpy as np
from empulse.models import CSLogitClassifier, RobustCSClassifier
from sklearn.datasets import make_classification

X, y = make_classification()
fn_cost = np.random.rand(y.size)  # instance-dependent cost
fp_cost = 5  # constant cost

model = RobustCSClassifier(CSLogitClassifier(C=0.1))
model.fit(X, y, fn_cost=fn_cost, fp_cost=fp_cost)

Example with passing instance-dependent costs through cross-validation:

import numpy as np
from empulse.models import CSBoostClassifier, RobustCSClassifier
from sklearn import set_config
from sklearn.datasets import make_classification
from sklearn.model_selection import cross_val_score
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler

set_config(enable_metadata_routing=True)

X, y = make_classification()
fn_cost = np.random.rand(y.size)
fp_cost = 5

pipeline = Pipeline([
    ('scaler', StandardScaler()),
    (
        'model',
        RobustCSClassifier(CSBoostClassifier()).set_fit_request(
            fn_cost=True, fp_cost=True
        ),
    ),
])

cross_val_score(pipeline, X, y, params={'fn_cost': fn_cost, 'fp_cost': fp_cost})

Example with passing instance-dependent costs through a grid search:

import numpy as np
from empulse.metrics import expected_cost_loss
from empulse.models import CSLogitClassifier, RobustCSClassifier
from sklearn import set_config
from sklearn.datasets import make_classification
from sklearn.model_selection import GridSearchCV
from sklearn.metrics import make_scorer
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler

set_config(enable_metadata_routing=True)

X, y = make_classification(n_samples=50)
fn_cost = np.random.rand(y.size)
fp_cost = 5

pipeline = Pipeline([
    ('scaler', StandardScaler()),
    (
        'model',
        RobustCSClassifier(CSLogitClassifier()).set_fit_request(
            fn_cost=True, fp_cost=True
        ),
    ),
])
param_grid = {'model__estimator__C': np.logspace(-5, 2, 5)}
scorer = make_scorer(
    expected_cost_loss,
    response_method='predict_proba',
    greater_is_better=False,
    normalize=True,
)
scorer = scorer.set_score_request(fn_cost=True, fp_cost=True)

grid_search = GridSearchCV(pipeline, param_grid=param_grid, scoring=scorer)
grid_search.fit(X, y, fn_cost=fn_cost, fp_cost=fp_cost)
fit(X, y, *, tp_cost=Parameter.UNCHANGED, tn_cost=Parameter.UNCHANGED, fn_cost=Parameter.UNCHANGED, fp_cost=Parameter.UNCHANGED, **fit_params)[source]#

Fit the estimator with the adjusted costs.

Parameters:
Xarray-like of shape (n_samples, n_features)
yarray-like of shape (n_samples,)
tp_costfloat or array-like, shape=(n_samples,), default=$UNCHANGED$

Cost of true positives. If float, then all true positives have the same cost. If array-like, then it is the cost of each true positive classification.

fp_costfloat or array-like, shape=(n_samples,), default=$UNCHANGED$

Cost of false positives. If float, then all false positives have the same cost. If array-like, then it is the cost of each false positive classification.

tn_costfloat or array-like, shape=(n_samples,), default=$UNCHANGED$

Cost of true negatives. If float, then all true negatives have the same cost. If array-like, then it is the cost of each true negative classification.

fn_costfloat or array-like, shape=(n_samples,), default=$UNCHANGED$

Cost of false negatives. If float, then all false negatives have the same cost. If array-like, then it is the cost of each false negative classification.

fit_paramsdict

Additional keyword arguments to pass to the estimator’s fit method.

Returns:
selfRobustCSLogitClassifier

Fitted RobustCSLogitClassifier model.

get_metadata_routing()#

Get metadata routing of this object.

Please check User Guide on how the routing mechanism works.

Returns:
routingMetadataRequest

A MetadataRequest encapsulating routing information.

get_params(deep=True)#

Get parameters for this estimator.

Parameters:
deepbool, default=True

If True, will return the parameters for this estimator and contained subobjects that are estimators.

Returns:
paramsdict

Parameter names mapped to their values.

score(X, y, sample_weight=None)#

Return the mean accuracy on the given test data and labels.

In multi-label classification, this is the subset accuracy which is a harsh metric since you require for each sample that each label set be correctly predicted.

Parameters:
Xarray-like of shape (n_samples, n_features)

Test samples.

yarray-like of shape (n_samples,) or (n_samples, n_outputs)

True labels for X.

sample_weightarray-like of shape (n_samples,), default=None

Sample weights.

Returns:
scorefloat

Mean accuracy of self.predict(X) w.r.t. y.

set_fit_request(*, fn_cost='$UNCHANGED$', fp_cost='$UNCHANGED$', tn_cost='$UNCHANGED$', tp_cost='$UNCHANGED$')#

Request metadata passed to the fit method.

Note that this method is only relevant if enable_metadata_routing=True (see sklearn.set_config). Please see User Guide on how the routing mechanism works.

The options for each parameter are:

  • True: metadata is requested, and passed to fit if provided. The request is ignored if metadata is not provided.

  • False: metadata is not requested and the meta-estimator will not pass it to fit.

  • None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.

  • str: metadata should be passed to the meta-estimator with this given alias instead of the original name.

The default (sklearn.utils.metadata_routing.UNCHANGED) retains the existing request. This allows you to change the request for some parameters and not others.

Added in version 1.3.

Note

This method is only relevant if this estimator is used as a sub-estimator of a meta-estimator, e.g. used inside a Pipeline. Otherwise it has no effect.

Parameters:
fn_coststr, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED

Metadata routing for fn_cost parameter in fit.

fp_coststr, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED

Metadata routing for fp_cost parameter in fit.

tn_coststr, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED

Metadata routing for tn_cost parameter in fit.

tp_coststr, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED

Metadata routing for tp_cost parameter in fit.

Returns:
selfobject

The updated object.

set_params(**params)#

Set the parameters of this estimator.

The method works on simple estimators as well as on nested objects (such as Pipeline). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object.

Parameters:
**paramsdict

Estimator parameters.

Returns:
selfestimator instance

Estimator instance.

set_score_request(*, sample_weight='$UNCHANGED$')#

Request metadata passed to the score method.

Note that this method is only relevant if enable_metadata_routing=True (see sklearn.set_config). Please see User Guide on how the routing mechanism works.

The options for each parameter are:

  • True: metadata is requested, and passed to score if provided. The request is ignored if metadata is not provided.

  • False: metadata is not requested and the meta-estimator will not pass it to score.

  • None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.

  • str: metadata should be passed to the meta-estimator with this given alias instead of the original name.

The default (sklearn.utils.metadata_routing.UNCHANGED) retains the existing request. This allows you to change the request for some parameters and not others.

Added in version 1.3.

Note

This method is only relevant if this estimator is used as a sub-estimator of a meta-estimator, e.g. used inside a Pipeline. Otherwise it has no effect.

Parameters:
sample_weightstr, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED

Metadata routing for sample_weight parameter in score.

Returns:
selfobject

The updated object.