AggregativeQuantifier#
- class mlquantify.base.AggregativeQuantifier[source]#
A base class for aggregative quantifiers.
This class provides the basic structure for aggregative quantifiers, which are quantifiers that aggregates a classifier or learner inside to generate predictions.
Inheriting from this class, it provides dynamic prediction for multiclass and binary data, making one-vs-all strategy for multiclass data with binary quantifiers.
Read more in the User Guide.
Notes
All quantifiers should specify at least the learner attribute. Wich should inherit from BaseEstimator of scikit-learn.
All quantifiers can return a dictionary with class:prevalence, a list or a numpy array.
Examples
Example 1: Multiclass Quantifier >>> from mlquantify.base import AggregativeQuantifier >>> from mlquantify.utils.general import get_real_prev >>> from sklearn.ensemble import RandomForestClassifier >>> from sklearn.model_selection import train_test_split >>> import numpy as np >>> class MyQuantifier(AggregativeQuantifier): … def __init__(self, learner, *, param): … self.learner = learner … self.param = param … def _fit_method(self, X, y): … self.learner.fit(X, y) … return self … def _predict_method(self, X): … predicted_labels = self.learner.predict(X) … class_counts = np.array([np.count_nonzero(predicted_labels == _class) for _class in self.classes]) … return class_counts / len(predicted_labels) >>> quantifier = MyQuantifier(learner=RandomForestClassifier(), param=1) >>> quantifier.get_params(deep=False) {‘learner’: RandomForestClassifier(), ‘param’: 1} >>> # Sample data >>> X = np.array([[0.1, 0.2], [0.2, 0.1], [0.3, 0.4], [0.4, 0.3], … [0.5, 0.6], [0.6, 0.5], [0.7, 0.8], [0.8, 0.7], … [0.9, 1.0], [1.0, 0.9]]) >>> y = np.array([0, 0, 0, 1, 0, 1, 0, 1, 0, 1]) # 40% positive (4 out of 10) >>> # Split the data into training and testing sets >>> X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42) >>> # Fit the quantifier >>> quantifier.fit(X_train, y_train) None >>> # Real prevalence in the training set >>> get_real_prev(y_train) {0: 0.5714285714285714, 1: 0.42857142857142855} >>> # Predicted prevalence in the test set >>> quantifier.predict(X_test) {0: 0.6666666666666666, 1: 0.3333333333333333}
Example 2: Binary Quantifier >>> from sklearn.svm import SVC >>> class BinaryQuantifier(AggregativeQuantifier): … @property … def is_multiclass(self): … return False … def __init__(self, learner): … self.learner = learner … def _fit_method(self, X, y): … self.learner.fit(X, y) … return self … def _predict_method(self, X): … predicted_labels = self.learner.predict(X) … class_counts = np.array([np.count_nonzero(predicted_labels == _class) for _class in self.classes]) … return class_counts / len(predicted_labels) >>> binary_quantifier = BinaryQuantifier(learner=SVC(probability=True)) >>> # Sample multiclass data >>> X = np.array([ … [0.1, 0.2], [0.2, 0.1], [0.3, 0.4], [0.4, 0.3], … [0.5, 0.6], [0.6, 0.5], [0.7, 0.8], [0.8, 0.7], … [0.9, 1.0], [1.0, 0.9], [1.1, 1.2], [1.2, 1.1], … [1.3, 1.4], [1.4, 1.3], [1.5, 1.6], [1.6, 1.5], … [1.7, 1.8], [1.8, 1.7], [1.9, 2.0], [2.0, 1.9] … ]) >>> # Update the labels to include a third class >>> y = np.array([0, 0, 0, 1, 0, 1, 0, 1, 2, 2, 0, 1, 0, 1, 0, 1, 2, 2, 0, 1]) >>> # Split the data into training and testing sets >>> X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.4, random_state=42) >>> # Fit the binary quantifier >>> binary_quantifier.fit(X_train, y_train) None >>> # Real prevalence in the training set >>> get_real_prev(y_test) {0: 0.25, 1: 0.5, 2: 0.25} >>> preds = binary_quantifier.predict(X_test) >>> preds {0: 1.0, 1: 0.0, 2: 0.0}
- 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_probabilistic: bool[source]#
Check if the learner is probabilistic or not.
- Returns:
- bool
True if the learner is probabilistic, False otherwise.
- 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 directlyestimate 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$') AggregativeQuantifier [source]#
Request metadata passed to the
fit
method.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 tofit
if 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.
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 infit
.- learner_fittedstr, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED
Metadata routing for
learner_fitted
parameter infit
.- n_jobsstr, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED
Metadata routing for
n_jobs
parameter infit
.
- 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.