DyS#

class mlquantify.matching.DyS(estimator=None, bins_size=None, strategy='ovr', cv=None, stratified=True, shuffle=False, random_state=None, distance='topsoe', solver='auto', bin_strategy=None, laplace_smoothing=False)[source]#

Distribution y-Similarity (DyS) quantifier.

Targets prior probability shift. A general mixture-model (distribution matching) quantifier: it builds class-conditional score histograms from cross-validated classifier scores and searches for the positive-class mixture proportion whose mixed histogram minimises a chosen dissimilarity to the test score histogram. Generalises HDy to any distance (Topsoe by default). Binary-only; requires soft scores; multiclass via one-vs-rest (OvR).

Parameters:
estimatorestimator, optional

A probabilistic classifier with fit and predict_proba methods.

bins_sizeint or array-like or None, default=None

Histogram bin count(s) to sweep over; controls histogram resolution. Defaults to a logarithmic grid. Estimates over the bin counts are aggregated by their median.

distancestr, default=’topsoe’

Dissimilarity minimised between the mixed and test histograms.

  • 'topsoe' : symmetric information-theoretic distance; the best general performer (recommended).

  • 'hellinger' : bounded sqrt-probability distance (the HDy choice).

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

  • 'sqEuclidean' : squared Euclidean distance between bin vectors.

solver{‘auto’, ‘ternary’, ‘grid’, ‘bounded’}, default=’auto’

Search strategy over the mixture proportion alpha.

  • 'auto' : pick a sensible default (bounded scalar search).

  • 'ternary' : interval-trisection search; fast on the near-unimodal objective.

  • 'grid' : exhaustive search over an evenly-spaced grid of alpha.

  • 'bounded' : scipy bounded scalar minimiser.

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

Multiclass decomposition strategy.

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

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

cvint or None, default=None

Cross-validation folds for computing training scores.

stratifiedbool, default=True

Whether to stratify CV splits.

shufflebool, default=False

Whether to shuffle data before splitting.

random_stateint or None, default=None

Random seed for reproducibility.

bin_strategy{‘median’, ‘mean’, None}, default=None

How per-bin-block prevalence estimates are aggregated when the histogram is partitioned into blocks; None disables block partitioning.

laplace_smoothingbool, default=False

If True, add a small count to every bin before normalising, stabilising ratio/log-based distances when some bins are empty.

Attributes:
estimator_estimator

The fitted underlying classifier.

classes_ndarray of shape (n_classes,)

Class labels seen during fit.

See also

HDy

Hellinger-distance special case.

SORD

Bin-free ordinal-distance member of the same framework.

SMM

Mean-matching member of the same framework.

Notes

DyS generalises HDy: with distance='hellinger' the two coincide. Best bin counts are typically small (around 20 or fewer); the median over swept bin counts makes the estimate robust to bin mis-specification.

References

References
[1]

Maletzke, A., dos Reis, D., Cherman, E., & Batista, G. (2019). DyS: A Framework for Mixture Models in Quantification. AAAI, pp. 4552–4560.

Examples

>>> 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 = DyS(estimator=LogisticRegression()).fit(X, y)
>>> q.predict(X)
{0: ..., 1: ...}
>>> # call aggregate with pre-computed posterior scores
>>> scores = q.estimator_.predict_proba(X)
>>> q.aggregate(scores, scores, y)
{0: ..., 1: ...}
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: ...}
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_distance(dist_train, dist_test, distance='hellinger')[source]#

Compute a distance between two normalized representations.

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_fit_request(*, cv_prediction: bool | None | str = '$UNCHANGED$', estimator_fitted: bool | None | str = '$UNCHANGED$', sample_weight: bool | None | str = '$UNCHANGED$') DyS[source]#

Configure whether metadata should be requested to be passed to the fit method.

Note that this method is only relevant when this estimator is used as a sub-estimator within a meta-estimator and metadata routing is enabled with enable_metadata_routing=True (see sklearn.set_config). Please check the 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.

Parameters:
cv_predictionstr, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED

Metadata routing for cv_prediction parameter in fit.

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

Metadata routing for estimator_fitted parameter in fit.

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

Metadata routing for sample_weight parameter in fit.

Returns:
selfobject

The updated object.

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.