MS2#

class mlquantify.methods.aggregative.MS2(learner: BaseEstimator | None = None)[source]#

Median Sweep 2 (MS2). This method is an extension of the Median Sweep strategy, but it focuses only on cases where the difference between the true positive rate (TPR) and the false positive rate (FPR) exceeds a threshold (0.25). The method computes the median values of TPR, FPR, and thresholds for these selected cases.

Parameters:
learnerBaseEstimator

A scikit-learn compatible classifier to be used for quantification.

Attributes:
learnerBaseEstimator

Returns the learner_ object.

See also

ThresholdOptimization

Base class for threshold-based quantification methods.

ACC

Adjusted Classify and Count quantification method.

MS

Median Sweep quantification method.

CC

Classify and Count quantification method.

References

FORMAN, George. Quantifying counts and costs via classification. Data Mining and Knowledge Discovery, v. 17, p. 164-206, 2008. Available at: https://link.springer.com/article/10.1007/s10618-008-0097-y

Examples

>>> from mlquantify.methods.aggregative import MS2
>>> from mlquantify.utils.general import get_real_prev
>>> from sklearn.datasets import load_breast_cancer
>>> from sklearn.svm import SVC
>>> from sklearn.model_selection import train_test_split
>>>
>>> features, target = load_breast_cancer(return_X_y=True)
>>>
>>> X_train, X_test, y_train, y_test = train_test_split(features, target, test_size=0.2, random_state=42)
>>>
>>> ms2 = MS2(learner=SVC(probability=True))
>>> ms2.fit(X_train, y_train)
>>> y_pred = ms2.predict(X_test)
>>> y_pred
{0: 0.41287676595138967, 1: 0.5871232340486103}
>>> get_real_prev(y_test)
{0: 0.3991228070175439, 1: 0.6008771929824561}
best_tprfpr(thresholds: ndarray, tprs: ndarray, fprs: ndarray) tuple[source]#

Determines the optimal threshold, TPR, and FPR by focusing only on cases where the absolute difference between TPR and FPR is greater than 0.25. For these cases, the method computes the median values.

Parameters:
thresholdsnp.ndarray

An array of threshold values.

tprsnp.ndarray

An array of true positive rates corresponding to the thresholds.

fprsnp.ndarray

An array of false positive rates corresponding to the thresholds.

Returns:
tuple

A tuple containing: - The median threshold value for cases meeting the condition (float). - The median true positive rate for cases meeting the condition (float). - The median false positive rate for cases meeting the condition (float).

Raises:
ValueError

If no cases satisfy the condition |TPR - FPR| > 0.25.

Warning

If all TPR or FPR values are zero.

delayed_fit(class_, X, y)[source]#

Delayed fit method for one-vs-all strategy, with parallel execution.

Parameters:
class_Any

The class for which the model is being fitted.

Xarray-like

Training features.

yarray-like

Training labels.

Returns:
selfobject

Fitted binary quantifier for the given class.

delayed_predict(class_, X)[source]#

Delayed predict method for one-vs-all strategy, with parallel execution.

Parameters:
class_Any

The class for which the model is making predictions.

Xarray-like

Test features.

Returns:
float

Predicted prevalence for the given class.

fit(X, y, learner_fitted=False, cv_folds: int = 10, n_jobs: int = 1)[source]#

Fit the quantifier model.

Parameters:
Xarray-like

Training features.

yarray-like

Training labels.

learner_fittedbool, default=False

Whether the learner is already fitted.

cv_foldsint, default=10

Number of cross-validation folds.

n_jobsint, default=1

Number of parallel jobs to run.

Returns:
selfobject

The fitted quantifier instance.

Notes

The model dynamically determines whether to perform one-vs-all classification or to directly fit the data based on the type of the problem: - If the data is binary or inherently multiclass, the model fits directly using

_fit_method without creating binary quantifiers.

  • For other cases, the model creates one binary quantifier per class using the one-vs-all approach, allowing for dynamic prediction based on the provided dataset.

fit_learner(X, y)[source]#

Fit the learner to the training data.

Parameters:
Xarray-like

Training features.

yarray-like

Training labels.

get_metadata_routing()[source]#

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)[source]#

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.

property is_multiclass: bool[source]#

Returns whether the method is applicable to multiclass quantification.

Threshold-based methods are typically binary classifiers, so this method returns False.

Returns:
bool

False, indicating that this method does not support multiclass quantification.

property is_probabilistic: bool[source]#

Returns whether the method is probabilistic.

This method is used to determine whether the quantification method is probabilistic, meaning it uses class-conditional probabilities to estimate class prevalences.

Returns:
bool

True, indicating that this method is probabilistic.

property learner[source]#

Returns the learner_ object. Returns ——- learner_ : object

The learner_ object stored in the class instance.

predict(X) dict[source]#

Predict class prevalences for the given data.

Parameters:
Xarray-like

Test features.

Returns:
dict

A dictionary where keys are class labels and values are their predicted prevalences.

Notes

The prediction approach is dynamically chosen based on the data type: - For binary or inherently multiclass data, the model uses _predict_method to directly

estimate class prevalences.

  • For other cases, the model performs one-vs-all prediction, where each binary quantifier estimates the prevalence of its respective class. The results are then normalized to ensure they form valid proportions.

predict_learner(X)[source]#

Predict the class labels or probabilities for the given data.

Parameters:
Xarray-like

Test features.

Returns:
array-like

The predicted class labels or probabilities.

set_fit_request(*, cv_folds: bool | None | str = '$UNCHANGED$', learner_fitted: bool | None | str = '$UNCHANGED$', n_jobs: bool | None | str = '$UNCHANGED$') MS2[source]#

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

Metadata routing for cv_folds parameter in fit.

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

Metadata routing for learner_fitted parameter in fit.

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

Metadata routing for n_jobs parameter in fit.

Returns:
selfobject

The updated object.

set_params(**params)[source]#

Set the parameters of this estimator. The method allows setting parameters for both the model and the learner. Parameters that match the model’s attributes will be set directly on the model. Parameters prefixed with ‘learner__’ will be set on the learner if it exists. Parameters: ———– **params : dict

Dictionary of parameters to set. Keys can be model attribute names or ‘learner__’ prefixed names for learner parameters.

Returns:#

selfQuantifier

Returns the instance of the quantifier with updated parameters itself.