MRCpy.BaseMRC¶
- class MRCpy.BaseMRC(loss='0-1', s=0.3, deterministic=True, random_state=None, fit_intercept=True, phi='linear', **phi_kwargs)[source]¶
Base class for different minimax risk classifiers
This class is a parent class for different MRCs implemented in the library. It defines the different parameters and the layout.
See also
For more information about MRC, one can refer to the following resources:
- Parameters:
- lossstr, default=’0-1’
Type of loss function to use for the risk minimization. The options are 0-1 loss and logarithmic loss.
'0-1': 0-1 loss quantifies the probability of classification error at a certain example for a certain rule.'log': Log-loss quantifies the minus log-likelihood at a certain example for a certain rule.
- sfloat, default=0.3
Parameter that tunes the estimation of expected values of feature mapping function. It is used to calculate \(\boldsymbol{\lambda}\) (variance in the mean estimates for the expectations of the feature mappings) in the following way
\[\boldsymbol{\lambda} = s * \text{std}(\Phi(X,Y)) / \sqrt{\left| X \right|}\]where (X,Y) is the dataset of training samples and their labels respectively and \(\text{std}(\Phi(X,Y))\) stands for standard deviation of \(\Phi(X,Y)\) in the supervised dataset (X,Y).
- deterministicbool, default=True
Whether the prediction of the labels should be done in a deterministic way (given a fixed
random_statein the case of using random Fourier or random ReLU features).- random_stateint, RandomState instance, default=None
Random seed used when ‘fourier’ and ‘relu’ options for feature mappings are used to produce the random weights.
- fit_interceptbool, default=True
Whether to calculate the intercept for MRCs. If set to false, no intercept will be used in calculations (i.e. data is expected to be already centered).
- phistr or BasePhi instance, default=’linear’
Type of feature mapping function to use for mapping the input data. The currently available feature mapping methods are ‘fourier’, ‘relu’, ‘threshold’ and ‘linear’. The users can also implement their own feature mapping object (should be a
BasePhiinstance) and pass it to this argument. Note that when using ‘fourier’ or ‘relu’ feature mappings, training and testing instances are expected to be normalized. To implement a feature mapping, please go through the Feature Mappings section.- ‘linear’
It uses the identity feature map referred to as Linear feature map. See class
BasePhi.- ‘fourier’
It uses Random Fourier Feature map. See class
RandomFourierPhi.- ‘relu’
It uses Rectified Linear Unit (ReLU) features. See class
RandomReLUPhi.- ‘threshold’
It uses Feature mappings obtained using a threshold. See class
ThresholdPhi.
- **phi_kwargsAdditional parameters for feature mappings.
Groups the multiple optional parameters for the corresponding feature mappings (
phi).For example in case of fourier features, the number of features is given by
n_componentsparameter which can be passed as argument -MRC(loss='log', phi='fourier', n_components=500)The list of arguments for each feature mappings class can be found in the corresponding documentation.
- Attributes:
- is_fitted_bool
Whether the classifier is fitted i.e., the parameters are learnt.
- tau_matarray-like of shape (n_classes, n_features)
Mean estimates for the expectations of feature mappings.
- lambda_matarray-like of shape (n_classes, n_features)
Variance in the mean estimates for the expectations of the feature mappings.
- classes_array-like of shape (n_classes,)
Labels in the given dataset. If the labels Y are not given during fit i.e., tau and lambda are given as input, then this array is None.
Methods
error(X, Y)Return the mean error obtained for the given test data and labels.
fit(X, Y[, X_])Fit the MRC model.
Get metadata routing of this object.
get_params([deep])Get parameters for this estimator.
minimax_risk(X, tau_mat, lambda_mat, n_classes)Abstract function for sub-classes implementing the different MRCs.
predict(X)Predicts classes for new instances using a fitted model.
Abstract function for sub-classes implementing the different MRCs.
score(X, y[, sample_weight])Return the mean accuracy on the given test data and labels.
set_fit_request(*[, X_])Request metadata passed to the
fitmethod.set_params(**params)Set the parameters of this estimator.
set_score_request(*[, sample_weight])Request metadata passed to the
scoremethod.- __init__(loss='0-1', s=0.3, deterministic=True, random_state=None, fit_intercept=True, phi='linear', **phi_kwargs)[source]¶
Initialize self. See help(type(self)) for accurate signature.
- error(X, Y)[source]¶
Return the mean error obtained for the given test data and labels.
- Parameters:
- Xarray-like of shape (n_samples, n_dimensions)
Test instances for which the labels are to be predicted by the MRC model.
- Yarray-like of shape (n_samples, 1), default=None
Labels corresponding to the testing instances used to compute the error in the prediction.
- Returns:
- errorfloat
Mean error of the learned MRC classifier
- fit(X, Y, X_=None)[source]¶
Fit the MRC model.
Computes the parameters required for the minimax risk optimization and then calls the
minimax_riskfunction to solve the optimization.- Parameters:
- Xarray-like of shape (n_samples, n_dimensions)
Training instances used in
Calculating the expectation estimates that constrain the uncertainty set for the minimax risk classification
Solving the minimax risk optimization problem.
n_samplesis the number of training samples andn_dimensionsis the number of features.- Yarray-like of shape (n_samples, 1), default=None
Labels corresponding to the training instances used only to compute the expectation estimates.
- X_array-like of shape (n_samples2, n_dimensions), default=None
These instances are optional and when given, will be used in the minimax risk optimization. These extra instances are generally a smaller set and give an advantage in training time.
- Returns:
- self :
Fitted estimator
- get_metadata_routing()¶
Get metadata routing of this object.
Please check User Guide on how the routing mechanism works.
- Returns:
- routingMetadataRequest
A
MetadataRequestencapsulating 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.
- minimax_risk(X, tau_mat, lambda_mat, n_classes)[source]¶
Abstract function for sub-classes implementing the different MRCs.
Solves the minimax risk optimization problem for the corresponding variant of MRC.
- Parameters:
- Xarray-like of shape (n_samples, n_dimensions)
Training instances used for solving the minimax risk optimization problem.
- tau_matarray-like of shape (n_classes, n_features)
Mean estimates \(oldsymbol{ au}\) corresponding with the expectations of feature mappings.
- lambda_matarray-like of shape (n_classes, n_features)
Inaccuracies \(oldsymbol{\lambda}\) in the mean estimates corresponding with the expectations of the feature mappings.
- n_classesint
Number of labels in the dataset.
- Returns:
- self :
Fitted estimator
- predict(X)[source]¶
Predicts classes for new instances using a fitted model.
Returns the predicted classes for the given instances in
Xusing the probabilities given by the functionpredict_proba.- Parameters:
- Xarray-like of shape (n_samples, n_dimensions)
Test instances for which the labels are to be predicted by the MRC model.
- Returns:
- y_predarray-like of shape (n_samples,)
Predicted labels corresponding to the given instances.
- predict_proba(X)[source]¶
Abstract function for sub-classes implementing the different MRCs.
Computes conditional probabilities corresponding to each class for the given unlabeled instances.
- Parameters:
- Xarray-like of shape (n_samples, n_dimensions)
Testing instances for which the prediction probabilities are calculated for each class.
- Returns:
- hy_xarray-like of shape (n_samples, n_classes)
Conditional probabilities (\(p(y|x)\)) corresponding to each class.
- 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(*, X_: Union[bool, None, str] = '$UNCHANGED$') → MRCpy.base_mrc.BaseMRC¶
Request metadata passed to the
fitmethod.Note that this method is only relevant if
enable_metadata_routing=True(seesklearn.set_config()). Please see 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.New 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:
- X_str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED
Metadata routing for
X_parameter infit.
- 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: Union[bool, None, str] = '$UNCHANGED$') → MRCpy.base_mrc.BaseMRC¶
Request metadata passed to the
scoremethod.Note that this method is only relevant if
enable_metadata_routing=True(seesklearn.set_config()). Please see 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.New 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_weightparameter inscore.
- Returns:
- selfobject
The updated object.
Examples using
MRCpy.BaseMRC¶
Example: Use of DWGCS (Double-Weighting General Covariate Shift) for Covariate Shift Adaptation
Example: Use of DWGCS (Double-Weighting General Covariate Shift) for Covariate Shift Adaptation