WeightedAnDE#

class skbn.WeightedAnDE(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', average='joint', weight_scope='component', weight_level=1, l2_reg=1.0, max_iter=1000, tol=1e-06, modular=False, continuous_children='gaussian')#

Weighted Averaged n-Dependence Estimators (WeightedAnDE) [Hybrid].

Discriminative weights learned on top of the generative AnDE by maximising the conditional log-likelihood with L-BFGS-B, pre-conditioned by the generative parameters (the weights start at, and are regularized towards, the generative model). weight_scope sets what each weight multiplies and mean how the components are pooled.

Component weights (weight_scope="component") weight each SPnDE as a whole. With the arithmetic mean they are mixture coefficients,

\[s(y, x) = \log \sum_m w_m(y, x_p)\, P_m(y, x),\]

optimized in log-space (w = exp(theta)); since \(P_m = P(y, x_p) \prod_i P(x_i | y, x_p)\), level 4 is a discriminative re-estimation of each component’s root table \(P(y, x_p)\), and the lower levels tie its entries. Level 3 is the per-SPODE, per-class weighting of EODE-CLL [2] (without its attribute weights). With the geometric mean they scale each component’s log-joint, \(s = \frac{1}{|M|} \sum_m w_m \log P_m(y, x)\), with non-negative weights. Component weights do not change how a component combines its attributes, so they cannot correct a dependence between children shared by every component (e.g. a duplicated attribute).

Factor weights (weight_scope="factor") apply the weighted CCBN of Zaidi et al. [1] inside each SPnDE: every factor f of component m gets its own exponent, \(P_m^w(y, x) = \prod_f \theta_f^{w_f}\), and the components are pooled as above. The root factor \(P(y, x_p)\) is weighted as one factor whose value is the parent instantiation.

With modular=True the weights of each SPnDE are fitted on that component’s own conditional log-likelihood, a convex problem. Factor weights at level 4, fitted modularly and pooled with average="posterior", are the AnDE^w of FedAnDE [3]: one wCCBN per SPnDE, whose posteriors are averaged. The joint fit of an arithmetic mixture is non-convex; the geometric mean gives a convex joint problem.

Weight levels (variables indexing each weight, from coarsest to finest):

Level

weight_scope="component"

weight_scope="factor" [1]

1

Component

Factor

2

Component x parent value

Factor x value

3

Component x class

Factor x value x class

4

Component x class x parent value

Factor x value x class x parents

The value of a Gaussian child is not discretized, so its factor weights ignore the “value” dimension. Only the combinations that occur in training get a weight; the others share one weight that keeps its generative value, so the number of weights is bounded by the data, not by the cardinalities of the attributes. Factor weights keep the per-factor log-likelihoods of the training set in memory, about 12 * n_samples * n_classes * n_models * (n_features - n_dependence + 1) bytes.

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; 0 gives the Naive Bayes topology.

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 additive (Laplace/Lidstone) smoothing parameter for the probabilities of the generative model.

n_jobsint, default=None

Number of threads used to count and evaluate the SPnDEs; the weights are optimized in a single thread. 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.

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

Pooling of the (weighted) components.

average{“joint”, “posterior”}, default=”joint”

What the arithmetic mean pools: the components’ weighted joints \(P^w_m(y, x)\), as in AnDE, or their posteriors \(P^w_m(y | x)\). Both give the same geometric mean. With "posterior" a class-independent component weight cancels, so arithmetic component weights need a class-specific level (3 or 4).

weight_scope{“component”, “factor”}, default=”component”

Whether a weight multiplies a whole component or one of its factors.

weight_levelint, default=1

Granularity of the weights, from 1 (coarsest) to 4 (finest); see the table above.

l2_regfloat, default=1.0

Non-negative L2 regularization towards the generative solution (w = 1), added to the summed conditional log-likelihood.

max_iterint, default=1000

Maximum number of L-BFGS-B iterations (at least 1); with modular=True it applies to the fit of each component. A ConvergenceWarning is raised at the end of fit() when L-BFGS-B stops at max_iter before converging; increase max_iter or tol in that case.

tolfloat or None, default=1e-6

Stopping tolerance of L-BFGS-B on the relative reduction of the objective and on the projected gradient. None uses SciPy’s defaults, which are stricter on the objective (about 2e-9): they take about twice as many iterations for the same predictions.

modularbool, default=False

If True, the weights of each component are fitted independently on that component’s own conditional log-likelihood, which is convex. With arithmetic component weights only the class-specific levels (3 and 4) are identifiable; levels 1 and 2 reduce to the generative AnDE, the weights stay at 1 and a UserWarning is raised.

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 of the generative phase, 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.

coef_theta_ndarray of shape (n_weights,)

Optimized parameters: log w for arithmetic component weights (weight_scope="component" and mean="arithmetic"), w otherwise.

learned_weights_ndarray of shape (n_weights,)

Learned weights w.

n_weights_int

Number of weights, including the shared one for unseen combinations.

n_iter_int

Total number of L-BFGS-B iterations (summed over the components when modular=True).

See also

AnDE

The generative model.

GaussianALR

ALR^n on the factors of the SPnDEs.

References

[1] (1,2)

Zaidi, N. A., Webb, G. I., Carman, M. J., Petitjean, F., Buntine, W., Hynes, M., & De Sterck, H. (2017). Efficient parameter learning of Bayesian network classifiers. Machine Learning, 106(9-10), 1289-1329.

[2]

Zheng, X., Lin, Z., Xu, H., Chen, C., & Ye, T. (2015). Efficient learning ensemble SuperParent-one-dependence estimator by maximizing conditional log likelihood. Expert Systems with Applications, 42, 7732-7745.

[3]

Torrijos, P., Gámez, J. A., & Puerta, J. M. Federated Averaged n-Dependence Estimators. Manuscript, 2026.

Examples

>>> import numpy as np
>>> from skbn import WeightedAnDE
>>> 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])
>>> clf = WeightedAnDE().fit(X, y)
>>> clf.learned_weights_.shape  # a weight per SPnDE and a shared one
(4,)
>>> clf.score(X, y)
1.0

Methods

fit(X, y[, sample_weight])

Fit the generative ensemble, then learn the discriminative weights.

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.

weight_table([component, feature, as_frame])

Return the learned weights with the combinations they belong to.

property component_weights_#

Weights of every SPnDE component, a list with one array per component of shape (n_keys, n_classes) when class-specific and (n_keys, 1) otherwise.

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 generative ensemble, then learn the discriminative weights.

The SPnDEs are fitted by counting frequencies and the weights are optimized with L-BFGS-B on the conditional log-likelihood, starting at the generative model.

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_, from the weighted components. 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$') → WeightedAnDE#

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

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.

weight_table(component=None, feature=None, as_frame=False)#

Return the learned weights with the combinations they belong to.

With weight_scope="component", returns the weights of one component or of every component (when component=None). With weight_scope="factor", returns the weights of the root factor (feature=None) or of a child attribute inside component (which defaults to 0 when n_dependence=0).

Parameters:
componentint, str, tuple or None, default=None

Component index, parent feature name (for n_dependence=1), or tuple of parent features. With weight_scope="component", None returns all components together.

featureint, str or None, default=None

Child attribute (for weight_scope="factor"), by index or by name in feature_names_in_. None selects the root factor \(P(y, \mathbf{x}_P)\).

as_framebool, default=False

If True, return a pandas DataFrame.

Returns:
tableBunch or DataFrame

Dictionary-like object holding the decoded weights and labels.

Examples using skbn.WeightedAnDE#

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