MRCpy.CMRC

class MRCpy.CMRC(loss='0-1', s=0.3, deterministic=True, random_state=None, fit_intercept=True, solver='adam', alpha=0.01, stepsize='decay', mini_batch_size=None, max_iters=None, phi='linear', **phi_kwargs)[source]

Constrained Minimax Risk Classifier

The class CMRC implements the method Minimimax Risk Classifiers with fixed marginal distributions proposed in [1] using the additional marginals constraints on the instances. It also implements two kinds of loss functions, namely 0-1 and log loss.

This is a subclass of the super class BaseMRC.

See Examples of use for futher applications of this class and its methods.

Parameters:
lossstr {‘0-1’, ‘log’}, default = ‘0-1’

Type of loss function to use for the risk minimization. 0-1 loss quantifies the probability of classification error at a certain example for a certain rule. 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 \(\lambda\) (variance in the mean estimates for the expectations of the feature mappings) in the following way

\[\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_state in the case of using random Fourier or random ReLU features).

random_stateint, RandomState instance, default = None

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).

solver{‘cvx’, ‘sgd’, ‘adam’}, default = ’adam’

Method to use in solving the optimization problem. Default is ‘cvx’. To choose a solver, you might want to consider the following aspects:

’cvx’

Solves the optimization problem using the CVXPY library. Obtains an accurate solution while requiring more time than the other methods. Note that the library uses the GUROBI solver in CVXpy for which one might need to request for a license. A free license can be requested here

’sgd’

Solves the optimization using stochastic gradient descent. The parameters max_iters, stepsize and mini_batch_size determine the number of iterations, the learning rate and the batch size for gradient computation respectively. Note that the implementation uses nesterov’s gradient descent in case of ReLU and threshold features, and the above parameters do no affect the optimization in this case.

’adam’

Solves the optimization using stochastic gradient descent with adam (adam optimizer). The parameters max_iters, alpha and mini_batch_size determine the number of iterations, the learning rate and the batch size for gradient computation respectively. Note that the implementation uses nesterov’s gradient descent in case of ReLU and threshold features, and the above parameters do no affect the optimization in this case.

alphafloat, default = 0.001

Learning rate for ’adam’ solver.

stepsizefloat or {‘decay’}, default = ‘decay’

Learning rate for ’grad’ solver. The default is ‘decay’, that is, the learning rate decreases with the number of epochs of stochastic gradient descent.

mini_batch_sizeint, default = 1 or 32

The size of the batch to be used for computing the gradient in case of stochastic gradient descent and adam optimizer. In case of stochastic gradient descent, the default is 1, and in case of adam optimizer, the default is 32.

max_itersint, default = 100000 or 5000 or 2000

The maximum number of iterations to use in case of ’grad’ or ’adam’ solver. The default value is 100000 for ’grad’ solver and 5000 for ’adam’ solver and 2000 for nesterov’s gradient descent.

phistr or BasePhi instance, default = ‘linear’

The type of feature mapping function to use for mapping the input data. The currenlty available feature mapping methods are ‘fourier’, ‘relu’, ‘threshold’ and ‘linear’. The users can also implement their own feature mapping object (should be a BasePhi instance) 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_components parameter 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.

Examples

Simple example of using CMRC with default seetings: 0-1 loss and linear feature mapping. We first load the data and split it into train and test sets. We fit the model with the training samples using fit function. Then, we predict the class of some test samples with predict. We can also obtain the probabilities of each class with predict_proba. Finally, we calculate the score of the model over the test set using score.

>>> from MRCpy import CMRC
>>> from MRCpy.datasets import load_mammographic
>>> from sklearn import preprocessing
>>> from sklearn.model_selection import train_test_split
>>> # Loading the dataset
>>> X, Y = load_mammographic(return_X_y=True)
>>> # Split the dataset into training and test instances
>>> X_train, X_test, Y_train, Y_test =
train_test_split(X, Y, test_size=0.2, random_state=0)
>>> # Standarize the data
>>> std_scale = preprocessing.StandardScaler().fit(X_train, Y_train)
>>> X_train = std_scale.transform(X_train)
>>> X_test = std_scale.transform(X_test)
>>> # Fit the CMRC model
>>> clf = CMRC().fit(X_train, Y_train)
>>> # Prediction. The predicted values for the first 10 test instances are:
>>> clf.predict(X_test[:10, :])
[0 0 0 0 0 1 0 1 0 0]
>>> # Predicted probabilities.
>>> # The predicted probabilities for the first 10 test instances are:
>>> clf.predict_proba(X_test[:10, :])
[[0.62919573 0.37080427]
 [1.         0.        ]
 [0.95104266 0.04895734]
 [1.         0.        ]
 [0.99047735 0.00952265]
 [0.         1.        ]
 [1.         0.        ]
 [0.12378713 0.87621287]
 [1.         0.        ]
 [0.62290253 0.37709747]]
>>> # Calculate the score of the predictor
>>> # (mean accuracy on the given test data and labels)
>>> clf.score(X_test, Y_test)
0.8247422680412371
Attributes:
is_fitted_bool

Whether the classifier is fitted i.e., the parameters are learnt.

tau_array-like of shape (n_features) or float

Mean estimates for the expectations of feature mappings.

lambda_array-like of shape (n_features) or float

Variance in the mean estimates for the expectations of the feature mappings.

mu_array-like of shape (n_features) or float

Parameters learnt by the optimization.

params_dict

Dictionary that stores the optimal points and best value of the function.

Methods

compute_lambda(X, Y)

Compute deviation in the mean estimate tau using the given training instances.

compute_phi(X)

Compute the feature mapping corresponding to instances given for learning the classifiers (in case of training) and prediction (in case of testing).

compute_tau(X, Y)

Compute mean estimate tau using the given training instances.

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()

Get metadata routing of this object.

get_params([deep])

Get parameters for this estimator.

get_upper_bound()

Returns the upper bound on the expected loss for the fitted classifier.

minimax_risk(X, tau_, lambda_, n_classes)

Solves the marginally constrained minimax risk optimization problem for different types of loss (0-1 and log loss).

predict(X)

Predicts classes for new instances using a fitted model.

predict_proba(X)

Computes conditional probabilities corresponding to each class for the given unlabeled instances.

psi(mu, phi)

Function to compute the psi function in the objective using the given solution mu and the feature mapping corresponding to a single instance.

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 fit method.

set_params(**params)

Set the parameters of this estimator.

set_score_request(*[, sample_weight])

Request metadata passed to the score method.

__init__(loss='0-1', s=0.3, deterministic=True, random_state=None, fit_intercept=True, solver='adam', alpha=0.01, stepsize='decay', mini_batch_size=None, max_iters=None, phi='linear', **phi_kwargs)[source]
compute_lambda(X, Y)

Compute deviation in the mean estimate tau using the given training instances.

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

Training instances used for solving the minimax risk optimization problem.

Yarray-like of shape (n_samples, 1), default = None

Labels corresponding to the training instances used only to compute the expectation estimates.

compute_phi(X)

Compute the feature mapping corresponding to instances given for learning the classifiers (in case of training) and prediction (in case of testing).

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

Instances to be converted to features.

compute_tau(X, Y)

Compute mean estimate tau using the given training instances.

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

Training instances used for solving the minimax risk optimization problem.

Yarray-like of shape (n_samples, 1), default = None

Labels corresponding to the training instances used only to compute the expectation estimates.

error(X, Y)

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_risk function 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_samples is the number of training samples and n_features is 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 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.

get_upper_bound()[source]

Returns the upper bound on the expected loss for the fitted classifier.

Returns:
upper_boundfloat

Upper bound of the expected loss for the fitted classifier.

minimax_risk(X, tau_, lambda_, n_classes)[source]

Solves the marginally constrained minimax risk optimization problem for different types of loss (0-1 and log loss). When use_cvx=False, it uses SGD optimization for linear and random fourier feature mappings and nesterov subgradient approach for the rest.

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

Training instances used for solving the minimax risk optimization problem.

tau_array-like of shape (n_features * n_classes)

The mean estimates for the expectations of feature mappings.

lambda_array-like of shape (n_features * n_classes)

The variance in the mean estimates for the expectations of the feature mappings.

n_classesint

Number of labels in the dataset.

Returns:
self

Fitted estimator

predict(X)

Predicts classes for new instances using a fitted model.

Returns the predicted classes for the given instances in X using the probabilities given by the function predict_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]

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)

The conditional probabilities (p(y|x)) corresponding to each class.

psi(mu, phi)[source]

Function to compute the psi function in the objective using the given solution mu and the feature mapping corresponding to a single instance.

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_: bool | None | str = '$UNCHANGED$') CMRC

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:
X_str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED

Metadata routing for X_ 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: bool | None | str = '$UNCHANGED$') CMRC

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.

Examples using MRCpy.CMRC

Example: Predicting COVID-19 patients outcome using MRCs

Example: Predicting COVID-19 patients outcome using MRCs