AnDE#

class skbn.AnDE(n_dependence=1, n_bins=5, strategy='quantile', alpha=1.0, n_jobs=None, categorical_features=None, bernoulli_features=None, gaussian_features=None, var_prior_weight=1.0, min_parent_count=1, unseen_state='laplace', mean='arithmetic', continuous_children='gaussian')#

Averaged n-Dependence Estimators (AnDE) [Generative].

This is the generative model described by Webb et al. [1]: an ensemble of SPnDEs whose joint probabilities are pooled with the arithmetic mean,

\[P(y|x) \propto \frac{1}{|M|} \sum_{m} P_m(y, x).\]

With mean="geometric" the joints are pooled with the geometric mean instead, \(P(y|x) \propto \prod_m P_m(y, x)^{1/|M|}\). This logarithmic pool of SPnDEs is not the AnJE of Zaidi et al. [3], which pools n-joins \(P(x_\alpha | y)\) (see skbn.AnJE); for n_dependence=1 it equals \(P(y) \prod_{i<j} P(x_i, x_j | y)^{2/a} \prod_i P(x_i | y)^{-(a-2)/a}\) on discrete data.

This implementation extends the original AnDE by supporting mixed data types (Gaussian/Categorical) through the Super-Class strategy.

When a test instance falls in an augmented state \((y, \mathbf{x}_p)\) never seen in training, the child conditionals come from unseen_state; a SPnDE whose parent instantiation occurred fewer than min_parent_count times is left out of the pool for that instance, and the prediction falls back to Naive Bayes when no SPnDE qualifies.

Parameters:
n_dependenceint, default=1

Order n of the dependence, the number of super-parent attributes of each SPnDE. It must satisfy 0 <= n_dependence <= n_features.

  • n=0: Naive Bayes.

  • n=1: AODE (Averaged One-Dependence Estimators).

  • n=2: A2DE.

n_binsint, default=5

Number of bins for discretizing continuous attributes when they act as super-parents (at least 2). Children remain continuous and are modeled by Gaussian distributions.

strategy{‘uniform’, ‘quantile’, ‘kmeans’, ‘mdlp’}, default=’quantile’

Strategy used for the discretization of super-parents. 'mdlp' places the cuts with the supervised entropy discretization of Fayyad and Irani (see MDLPDiscretizer), which chooses the number of bins of each attribute, so n_bins is not used.

alphafloat, default=1.0

Non-negative Laplace smoothing of the estimates of the SPnDEs and of the augmented-class prior.

n_jobsint, default=None

Number of threads used to count and evaluate the SPnDEs. None means 1 unless in a joblib.parallel_backend context. -1 means using all processors.

categorical_featuresarray-like of int or bool, default=None

Indices (or a boolean mask) of the attributes to treat as categorical, passed to MixedNB, which describes how the undeclared attributes are typed.

bernoulli_featuresarray-like of int or bool, default=None

Indices (or a boolean mask) of the attributes to treat as Bernoulli. See MixedNB.

gaussian_featuresarray-like of int or bool, default=None

Indices (or a boolean mask) of the attributes to treat as Gaussian. See MixedNB.

var_prior_weightfloat, default=1.0

Pseudo-observations shrinking each Gaussian child variance towards the pooled variance of the feature (see MixedNB). It applies to the SPnDEs with super-parents and to the class-level back-off model; 0 gives the variances of GaussianNB.

min_parent_countint, default=1

Minimum training frequency of a parent instantiation for its SPnDE to take part in the prediction of an instance. 0 behaves as 1.

unseen_state{“laplace”, “backoff”}, default=”laplace”

Child conditionals used for an augmented state never seen in training. "laplace" is the standard smoothed estimate of an empty cell (uniform for discrete children, the pooled Gaussian of the attribute for continuous ones); "backoff" reuses the class-level conditionals. An ablation over the benchmark found no practical difference between them.

mean{“arithmetic”, “geometric”}, default=”arithmetic”

Pooling of the components’ joint probabilities.

continuous_children{“gaussian”, “discretized”}, default=”gaussian”

How a continuous attribute is modelled as a child. With "gaussian" it keeps its values and has a Gaussian conditional, and only its role as a parent uses the bins of n_bins and strategy. With "discretized" every continuous attribute is replaced by its bin, as a categorical attribute, in both roles: the model on discretized data of the original works, without a discretizer in a pipeline. Values beyond the training range fall in the first or the last bin.

Attributes:
classes_ndarray of shape (n_classes,)

Class labels.

class_count_ndarray of shape (n_classes,)

Number of training samples of each class.

n_features_in_int

Number of features seen during fit.

feature_names_in_ndarray of shape (n_features_in_,)

Names of features seen during fit. Defined only when X has feature names that are all strings.

ensemble_sequence of dict

The fitted SPnDEs, one per set of n_dependence super-parents (a single one for n_dependence=0). Each dict holds the "parent_indices" and "child_indices" of the component and the numbers of its parent instantiations ("n_parent_combos") and of the augmented states \(Y^*\) seen in training ("n_states"); the estimates of all the components are stored together in flat tables.

cut_points_list of ndarray or None

Cut-points of the continuous attributes, a list with an array per attribute that the model bins (as a parent, or as a child too with continuous_children="discretized") and None for the others.

feature_types_dict

Indices of the attributes of each type the model uses, under the keys “gaussian”, “categorical” and “bernoulli”.

backoff_MixedNB

Naive Bayes on the original class, used for the class-level conditionals, to resolve the type of every attribute and as the fallback when no SPnDE qualifies.

See also

WeightedAnDE

AnDE with discriminatively learned weights.

AnJE

Averaged n-Join Estimators.

MixedNB

Naive Bayes classifier for mixed data.

References

[1]

Webb, G. I., Boughton, J., & Wang, Z. (2005). Not so naive Bayes: Aggregating one-dependence estimators. Machine Learning, 58(1), 5-24.

[2]

Webb, G. I., Boughton, J., Zheng, F., Ting, K. M., & Salem, H. (2011). Learning by extrapolation from marginal to full-multivariate probability distributions: Decreasingly naive Bayesian classification. Machine Learning, 86(2), 233-272.

[3]

Zaidi, N. A., Webb, G. I., Carman, M. J., Petitjean, F., & Cerquides, J. (2016). ALR^n: Accelerated higher-order logistic regression. Machine Learning, 104(2-3), 151-194.

Examples

>>> import numpy as np
>>> from skbn import AnDE, MixedNB
>>> rng = np.random.RandomState(0)
>>> x0 = rng.randint(0, 2, size=200)
>>> x1 = rng.randint(0, 2, size=200)
>>> x2 = rng.randint(0, 3, size=200)  # noise
>>> y = x0 ^ x1  # exclusive or: no attribute is informative on its own
>>> X = np.column_stack([x0, x1, x2])
>>> MixedNB().fit(X, y).score(X, y) < 0.6
True
>>> clf = AnDE(n_dependence=1).fit(X, y)
>>> clf.score(X, y)
1.0

Methods

fit(X, y[, sample_weight])

Fit the ensemble of SPnDEs by counting frequencies.

get_metadata_routing()

Get metadata routing of this object.

get_params([deep])

Get parameters for this estimator.

predict(X)

Perform classification on an array of test vectors X.

predict_log_proba(X)

Return log-probability estimates for the test vector X.

predict_proba(X)

Return probability estimates for the test vector X.

score(X, y[, sample_weight])

Return accuracy on provided data and labels.

set_fit_request(*[, sample_weight])

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

set_params(**params)

Set the parameters of this estimator.

set_score_request(*[, sample_weight])

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

property cut_points_#

Cut-points of the continuous attributes, a list with an array per attribute that the model bins (as a parent, or as a child too with continuous_children="discretized") and None for the others. Bin b holds the values from cut_points_[i][b - 1] (included) to cut_points_[i][b], and the first and the last bin have no outer limit.

property feature_types_#

Indices of the attributes of each type the model uses, under the keys “gaussian”, “categorical” and “bernoulli”.

fit(X, y, sample_weight=None)#

Fit the ensemble of SPnDEs by counting frequencies.

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

Training vectors, where n_samples is the number of samples and n_features is the number of features. May contain missing values (NaN or missing labels).

yarray-like of shape (n_samples,)

Target values.

sample_weightarray-like of shape (n_samples,), default=None

Non-negative weights applied to individual samples.

Returns:
selfobject

Returns the instance itself.

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.

predict(X)#

Perform classification on an array of test vectors X.

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

The input samples.

Returns:
Cndarray of shape (n_samples,)

Predicted target values for X.

predict_log_proba(X)#

Return log-probability estimates for the test vector X.

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

The input samples.

Returns:
Cndarray of shape (n_samples, n_classes)

Log-probability of the samples for each class, in the order of classes_. The estimates are normalised over the classes and bounded below by the logarithm of the smallest positive float.

predict_proba(X)#

Return probability estimates for the test vector X.

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

The input samples.

Returns:
Cndarray of shape (n_samples, n_classes)

Probability of the samples for each class, in the order of classes_.

score(X, y, sample_weight=None)#

Return accuracy on provided 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(*, sample_weight: bool | None | str = '$UNCHANGED$') → AnDE#

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:
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)#

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$') → AnDE#

Configure whether metadata should be requested to be passed to the score 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 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.

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 skbn.AnDE#

Context-dependent rules on mixed data

Context-dependent rules on mixed data

XOR problem: AnDE and Naive Bayes

XOR problem: AnDE and Naive Bayes

Slice of the three-dimensional XOR problem

Slice of the three-dimensional XOR problem

Arithmetic or geometric mean with a failing sensor

Arithmetic or geometric mean with a failing sensor

Rare and unseen parent values

Rare and unseen parent values

Cost of the order of dependence

Cost of the order of dependence

Gaussian children or discretized attributes

Gaussian children or discretized attributes

Component or factor weights: data efficiency and cost

Component or factor weights: data efficiency and cost

Component weights as a selection of super-parents

Component weights as a selection of super-parents

Calibration of generative and weighted models

Calibration of generative and weighted models

A table of continuous measurements: what to expect

A table of continuous measurements: what to expect