fairlearn.preprocessing.PrototypeRepresentationLearner#
- class fairlearn.preprocessing.PrototypeRepresentationLearner(n_prototypes=2, reconstruct_weight=1.0, target_weight=1.0, fairness_weight=1.0, random_state=None, tol=1e-06, max_iter=1000)[source]#
A transformer and classifier that learns a latent representation of the input data to obfuscate the sensitive features while preserving the classification and reconstruction performance.
The model minimizes a loss function that consists of three terms: the reconstruction error, the classification error, and an approximation of the demographic parity difference.
Read more in the User Guide.
Added in version 0.13.0.
- Parameters:
n_prototypes (
int) – Number of prototypes to use in the latent representation.reconstruct_weight (
float) – Weight of the reconstruction error term in the objective function.target_weight (
float) – Weight of the classification error term in the objective function.fairness_weight (
float) – Weight of the fairness error term in the objective function.random_state (
int|RandomState|None) – Seed or random number generator for reproducibility.tol (
float) – Convergence tolerance for the optimization algorithm.max_iter (
int) – Maximum number of iterations for the optimization algorithm.
- Attributes:
- n_prototypes
int Number of prototypes to use in the latent representation.
- reconstruct_weight
float Weight of the reconstruction error term in the objective function.
- target_weight
float Weight of the classification error term in the objective function.
- fairness_weight
float Weight of the fairness error term in the objective function.
- random_state
int,np.random.RandomState, orNone Seed or random number generator for reproducibility.
- tol
float Tolerance for the optimization algorithm.
- max_iter
int Maximum number of iterations for the optimization algorithm.
- coef_
np.ndarray Coefficients of the learned model.
- n_iter_
int Number of iterations run by the optimization algorithm.
- n_features_in_
int Number of features in the input data.
- classes_
np.ndarrayorNone Unique classes in the target variable. Only set if target labels are provided during fitting, otherwise None.
- n_prototypes
Notes
The
PrototypeRepresentationLearnerimplements the algorithms intoduced in Zemel et al. [1].If no sensitive features are provided during fitting, the loss function will not include the fairness error term.
If no target labels are provided during fitting, the loss function will not include the classification error term and the model will not be able to predict probabilities or labels.
References
Examples
>>> import numpy as np >>> from fairlearn.preprocessing import PrototypeRepresentationLearner >>> X = np.array([[0, 1], [1, 0], [0, 0], [1, 1]]) >>> y = np.array([0, 1, 0, 1]) >>> sensitive_features = np.array([0, 0, 1, 1]) >>> prl = PrototypeRepresentationLearner(n_prototypes=2, random_state=42) >>> prl.fit(X, y, sensitive_features=sensitive_features) PrototypeRepresentationLearner(random_state=42) >>> X_transformed = prl.transform(X) >>> y_pred = prl.predict(X)
- fit(X, y=None, *, sensitive_features=None)[source]#
Fit the Prototype Representation Learner to the provided data.
- Parameters:
X (array_like of shape (n_samples, n_features)) – The input samples.
y (array_like of shape (n_samples,) or
None, default=None) – The target values.sensitive_features (array_like or
None, default=None) – Sensitive features to be considered whose groups will be used to promote demographic parity. If None, the fairness error term will not be included in the loss function.
- Return type:
- Returns:
self (PrototypeRepresentationLearner) – Returns the fitted instance.
- fit_transform(X, y=None, **fit_params)[source]#
Fit to data, then transform it.
Fits transformer to X and y with optional parameters fit_params and returns a transformed version of X.
- Parameters:
X (array_like of shape (n_samples, n_features)) – Input samples.
y (array_like of shape (n_samples,) or (n_samples, n_outputs), default=None) – Target values (None for unsupervised transformations).
**fit_params (
dict) – Additional fit parameters. Pass only if the estimator accepts additional params in its fit method.
- Returns:
X_new (
ndarrayarrayof shape (n_samples, n_features_new)) – Transformed array.
- get_metadata_routing()[source]#
Get metadata routing of this object.
Please check User Guide on how the routing mechanism works.
- Returns:
routing (MetadataRequest) – A
MetadataRequestencapsulating routing information.
- predict(X)[source]#
Predict the labels for the given input data.
- Parameters:
X (array_like of shape (n_samples, n_features)) – The input data to predict.
- Return type:
- Returns:
The predicted labels for the input data.
- Raises:
NotFittedError – If the estimator is not fitted yet.
ValueError – If no labels were provided during fitting.
- predict_proba(X)[source]#
Predict class probabilities for the input samples X.
- Parameters:
X (array_like of shape (n_samples, n_features)) – The input samples.
- Return type:
- Returns:
The class probabilities of the input samples. The first column represents the probability of the negative class, and the second column represents the probability of the positive class.
- Raises:
NotFittedError – If the estimator is not fitted yet.
ValueError – If no labels were provided during fitting.
- score(X, y, sample_weight=None)[source]#
Return accuracy on provided 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:
X (array_like of shape (n_samples, n_features)) – Test samples.
y (array_like of shape (n_samples,) or (n_samples, n_outputs)) – True labels for X.
sample_weight (array_like of shape (n_samples,), default=None) – Sample weights.
- Returns:
score (
float) – Mean accuracy ofself.predict(X)w.r.t. y.
- set_fit_request(*, sensitive_features='$UNCHANGED$')[source]#
Configure whether metadata should be requested to be passed to the
fitmethod.Note that this method is only relevant when this estimator is used as a sub-estimator within a meta-estimator and metadata routing is enabled with
enable_metadata_routing=True(seesklearn.set_config()). Please check the User Guide on how the routing mechanism works.The options for each parameter are:
True: metadata is requested, and passed tofitif provided. The request is ignored if metadata is not provided.False: metadata is not requested and the meta-estimator will not pass it tofit.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.
- set_output(*, transform=None)[source]#
Set output container.
Refer to the user guide for more details and Introducing the set_output API for an example on how to use the API.
- Parameters:
transform ({"default", "pandas", "polars"}, default=None) –
Configure output of transform and fit_transform.
”default”: Default output format of a transformer
”pandas”: DataFrame output
”polars”: Polars output
None: Transform configuration is unchanged
Added in version 1.4: “polars” option was added.
- Returns:
self (estimator instance) – Estimator instance.
- set_params(**params)[source]#
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:
**params (
dict) – Estimator parameters.- Returns:
self (estimator instance) – Estimator instance.
- set_score_request(*, sample_weight='$UNCHANGED$')[source]#
Configure whether metadata should be requested to be passed to the
scoremethod.Note that this method is only relevant when this estimator is used as a sub-estimator within a meta-estimator and metadata routing is enabled with
enable_metadata_routing=True(seesklearn.set_config()). Please check the User Guide on how the routing mechanism works.The options for each parameter are:
True: metadata is requested, and passed toscoreif provided. The request is ignored if metadata is not provided.False: metadata is not requested and the meta-estimator will not pass it toscore.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.
- transform(X)[source]#
Transform the input data X using the learned prototype representation.
Each sample is transformed to its associated learned latent mapping, i.e. the softmax of its negative distance to the prototypes.
- Parameters:
X (array_like of shape (n_samples, n_features)) – The input data to transform.
- Return type:
- Returns:
The transformed data.
Notes
This method checks if the model is fitted, validates the input data, and then applies the learned prototype representation.
- random_state: int | RandomState | None#