QuaDapt#

class mlquantify.meta.QuaDapt(quantifier, measure='topsoe', merging_factors=array([0.1, 0.3, 0.5, 0.7, 0.9]), strategy='ovr')[source]#

QuaDapt: drift-resilient quantification via parameter adaptation.

Targets general distribution shift / concept drift, not only prior shift. Wraps a soft base quantifier and, at prediction time, simulates training score distributions with MoSS at several overlap levels, selects the level whose mixed scores best match the test scores, and uses that synthetic set as the aggregation reference. Binary base method; multiclass via one-vs-rest.

Parameters:
quantifierBaseQuantifier

A soft (probabilistic) base aggregative quantifier.

measure{‘topsoe’, ‘hellinger’, ‘probsymm’, ‘sord’}, default=’topsoe’

Distance comparing each synthetic score set with the test scores, used to pick the best merging factor.

  • 'topsoe' : symmetric information-theoretic distance.

  • 'hellinger' : bounded sqrt-probability distance.

  • 'probsymm' : probabilistic symmetric chi-square distance.

  • 'sord' : Sample Ordinal Distance on the raw scores (bin-free).

merging_factorsarray-like, default=np.arange(0.1, 1.0, 0.2)

Candidate MoSS overlap levels m to evaluate; each sets how much the synthetic positive and negative scores overlap (0 = well separated, 1 = fully overlapping).

strategy{‘ovr’, ‘ovo’}, default=’ovr’

Multiclass decomposition strategy.

  • 'ovr' : one-vs-rest, one binary adaptation per class.

  • 'ovo' : one-vs-one, one binary adaptation per class pair.

Attributes:
classes_ndarray of shape (n_classes,)

Class labels seen during fit.

y_trainndarray of shape (n_samples,)

Training labels stored during fit.

See also

DyS

A common base quantifier for QuaDapt.

EnsembleQ

Ensemble wrapper for prior-shift robustness.

Notes

Built on MoSS (Model for Score Simulation): adapting the merging factor to the test scores makes a standard quantifier resilient when the score-distribution complexity drifts. Generalises DySyn (DyS + MoSS) to any classifier-based quantifier; only the quantifier’s score reference is adapted, with no classifier retraining.

References

References
[1]

Ortega, J. P., Luth Junior, L. F., Zalewski, W., & Maletzke, A. (2025). QuaDapt: Drift-Resilient Quantification via Parameters Adaptation. Proc. 5th Int. Workshop on Learning to Quantify (LQ 2025), p. 64.

[2]

Maletzke, A., dos Reis, D., Hassan, W., & Batista, G. (2021). Accurately Quantifying under Score Variability. ICDM 2021, pp. 1228–1233. (Model for Score Simulation, MoSS.)

Examples

>>> from mlquantify.meta import QuaDapt
>>> from mlquantify.matching import DyS
>>> from sklearn.linear_model import LogisticRegression
>>> from sklearn.datasets import make_classification
>>> X, y = make_classification(n_samples=200, random_state=42)
>>> q = QuaDapt(DyS(LogisticRegression())).fit(X, y)
>>> q.predict(X)
{0: ..., 1: ...}
>>> # call aggregate with pre-computed posteriors
>>> proba = LogisticRegression().fit(X, y).predict_proba(X)
>>> q.aggregate(proba, y)
{0: ..., 1: ...}
classmethod MoSS(n, alpha, merging_factor, classes=None, random_state=None)[source]#

Generate a synthetic binary score set via the Model for Score Simulation.

Positive scores are sampled as \(U^{\mathfrak{m}}\) and negative scores as \(1 - U^{\mathfrak{m}}\), where \(U \sim \mathrm{Uniform}(0,1)\) and \(\mathfrak{m}\) is the merging factor. A higher merging_factor produces more overlapping positive and negative score distributions.

Parameters:
nint

Total number of synthetic observations to generate.

alphafloat

Prevalence of the positive class in the synthetic set.

merging_factorfloat

Controls the overlap between positive and negative score distributions. Values close to 0 produce well-separated scores; values close to 1 produce heavily overlapping scores.

classesarray-like of length 2 or None, default=None

Class labels for the negative and positive class respectively. If None, labels 0 and 1 are used.

random_stateint or None, default=None

Unused; reserved for future reproducibility support.

Returns:
scoresndarray of shape (n, 2)

Synthetic soft predictions for each observation.

labelsndarray of shape (n,)

Class labels for each synthetic observation.

\[\mathrm{MoSS}(n, \alpha, \mathfrak{m}) = \mathrm{syn}(\oplus, \lfloor \alpha n \rfloor, \mathfrak{m}) \cup \mathrm{syn}(\ominus, \lfloor (1-\alpha) n \rfloor, \mathfrak{m})\]

Notes

Only binary score generation is supported. The method is used internally by aggregate to build a synthetic training reference for the base quantifier.

References

References
[1]

Maletzke, A., Reis, D., Hassan, W., & Batista, G. (2021). Accurately Quantifying under Score Variability. ICDM 2021, pp. 1228–1233.

Examples

>>> from mlquantify.meta import QuaDapt
>>> scores, labels = QuaDapt.MoSS(n=1000, alpha=0.3, merging_factor=0.5)
>>> scores.shape
(1000, 2)
>>> labels.shape
(1000,)
aggregate(predictions, y_train, classes=None)[source]#

Aggregate posteriors into prevalences using MoSS score simulation.

Searches over merging_factors to find the synthetic score distribution (generated by MoSS) whose histogram is closest to the test score distribution, then passes that synthetic set as the training reference to the base quantifier’s aggregate.

Parameters:
predictionsndarray of shape (n_samples, n_classes)

Posterior probabilities of the test instances.

y_trainndarray of shape (n_train_samples,)

Training class labels used to resolve class ordering.

classesarray-like of shape (n_classes,) or None, default=None

Class labels the output must report, in order. When None they are inferred from y_train.

Returns:
prevalencesdict or ndarray of shape (n_classes,)

Estimated class prevalences.

Examples

>>> from mlquantify.meta import QuaDapt
>>> from mlquantify.matching import DyS
>>> from sklearn.linear_model import LogisticRegression
>>> from sklearn.datasets import make_classification
>>> X, y = make_classification(n_samples=200, random_state=42)
>>> q = QuaDapt(DyS(LogisticRegression())).fit(X, y)
>>> proba = LogisticRegression().fit(X, y).predict_proba(X)
>>> q.aggregate(proba, y)
{0: ..., 1: ...}
best_mixture(predictions)[source]#

Find the merging factor and prevalence that best match the test scores.

Evaluates each candidate value in merging_factors by generating a synthetic score set with MoSS and measuring its distance to the test distribution using the configured measure. Returns the merging factor, prevalence estimate, and distance for the best match.

Parameters:
predictionsndarray of shape (n_samples,) or (n_samples, 2)

Posterior probabilities or positive-class scores for the test set.

Returns:
best_alphafloat

Positive-class prevalence estimate under the best merging factor.

best_distancefloat

Distance between the test distribution and the best synthetic mix.

best_mfloat

Merging factor that achieved the lowest distance.

fit(X, y)[source]#

Fit the base classifier of the wrapped quantifier.

Only the underlying estimator is trained here; the full aggregation is deferred to aggregate so that the MoSS-based correction can be applied at prediction time.

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

Training feature matrix.

yarray-like of shape (n_samples,)

Training class labels.

Returns:
selfQuaDapt

The fitted quantifier.

Raises:
ValueError

If the wrapped quantifier does not use soft (probabilistic) predictions.

Examples

>>> from mlquantify.meta import QuaDapt
>>> from mlquantify.matching import DyS
>>> from sklearn.linear_model import LogisticRegression
>>> from sklearn.datasets import make_classification
>>> X, y = make_classification(n_samples=200, random_state=42)
>>> q = QuaDapt(DyS(LogisticRegression())).fit(X, y)
fit_predict(X, y, X_test)[source]#

Fit and predict class prevalences without storing models.

get_best_distance(predictions)[source]#

Return the minimum distribution distance achieved across all merging factors.

Parameters:
predictionsndarray of shape (n_samples,) or (n_samples, 2)

Posterior probabilities or positive-class scores for the test set.

Returns:
best_distancefloat

Lowest distance between the test distribution and any synthetic mix.

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.

predict(X)[source]#

Predict class prevalences using the MoSS adaptive correction.

Generates posterior probabilities for X with the fitted classifier and delegates to aggregate, which selects the best MoSS merging factor and calls the base quantifier’s aggregate.

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

Test feature matrix.

Returns:
prevalencesdict or ndarray of shape (n_classes,)

Estimated class prevalences.

Examples

>>> from mlquantify.meta import QuaDapt
>>> from mlquantify.matching import DyS
>>> from sklearn.linear_model import LogisticRegression
>>> from sklearn.datasets import make_classification
>>> X, y = make_classification(n_samples=200, random_state=42)
>>> q = QuaDapt(DyS(LogisticRegression())).fit(X, y)
>>> q.predict(X)
{0: ..., 1: ...}
save_quantifier(path: str | None = None) None[source]#

Save the quantifier instance to a file.

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:
**paramsdict

Estimator parameters.

Returns:
selfestimator instance

Estimator instance.