WeightedTAN#

class skbn.WeightedTAN(root=0, n_bins=5, strategy='quantile', alpha=1.0, categorical_features=None, bernoulli_features=None, gaussian_features=None, var_prior_weight=1.0, n_jobs=None, weight_level=4, l2_reg=1.0, max_iter=1000, tol=1e-06, continuous_children='gaussian')#

Discriminatively weighted Tree Augmented Naive Bayes.

The weighted conditionally Bayesian network (wCCBN) of Zaidi et al. [1] on the structure and the conditionals of TAN [2]: every parameter of the network gets an exponent weight,

\[P^w(y \mid \mathbf{x}) \propto P(y)^{w_y} \, P(x_r \mid y)^{w_{r, x_r, y}} \prod_{i \neq r} P(x_i \mid y, x_{\pi(i)})^{w_{i, x_i, y, x_{\pi(i)}}},\]

and the weights maximise the conditional log-likelihood of the training set, penalized by l2_reg * ||w - 1||^2, with L-BFGS-B and analytic gradients. The structure and the probabilities are those of TAN and stay fixed: the weights start at, and are regularized towards, the generative model (w = 1). The objective is convex in the weights.

The weights correct what the generative fit gets wrong when the data break the independence assumptions of the tree, for instance attributes that are correlated or duplicated beyond what one parent explains: they scale down the conditionals that count the same evidence twice.

Weight levels (variables indexing each weight, from coarsest to finest), the nested parameterizations of [1]:

Level

Variables

1

Factor

2

Factor x value

3

Factor x value x class

4

Factor x value x class x parents

A factor is the class prior \(P(y)\) or the conditional of an attribute; the class prior has a single value and no parents, so it gets one weight per class at levels 3 and 4. Level 4 (the default), one weight per parameter of the network, is the wCCBN of [1]: a reparameterization of the discriminative learning of the parameters of that network, which [1] found faster to optimize. The value of a Gaussian child is not discretized, so its 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. This is WeightedAnDE with weight_scope="factor" and mean="geometric" applied to the single network of TAN. A test instance in a parent state never seen in training gets the uninformed conditional of TAN. The fit keeps the per-factor log-likelihoods of the training set in memory, about 12 * n_samples * n_classes * (n_features + 1) bytes, and each evaluation of the objective costs as much.

Parameters:
rootint, default=0

Index of the attribute used as root of the tree, in [0, n_features - 1]. The root does not change the edges of the tree, only their direction, but with smoothing (alpha > 0) the estimates, and so the predictions, depend on the direction.

n_binsint, default=5

Number of bins used to discretize continuous attributes for the structure learning and when they act as parents. Continuous children remain continuous.

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

Strategy used for the discretization of continuous attributes. '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 discrete conditional probability tables.

categorical_featuresarray-like of int or bool, default=None

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

bernoulli_featuresarray-like of int or bool, default=None

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

gaussian_featuresarray-like of int or bool, default=None

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

var_prior_weightfloat, default=1.0

Non-negative number of pseudo-observations shrinking each Gaussian variance towards the pooled variance of the feature (see MixedNB).

n_jobsint, default=None

Number of threads used to compute the conditional mutual information and to count and evaluate the conditionals; the weights are optimized in a single thread. None means 1 and -1 all the processors.

weight_levelint, default=4

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). 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.

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 known to the classifier.

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.

conditional_mutual_info_ndarray of shape (n_features, n_features)

Empirical conditional mutual information \(I(A_i; A_j \mid C)\) (in nats) between every pair of (discretized) attributes.

parents_ndarray of shape (n_features,)

Attribute parent of every attribute in the tree, -1 for the root.

edges_list of tuple of int

Arcs between attributes, as (parent, child) pairs of feature indices in the order of the children.

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. Provides the class prior, the root conditional and the detected feature types (feature_types_).

learned_weights_ndarray of shape (n_weights,)

Learned weights w.

n_weights_int

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

prior_weights_ndarray of shape (n_classes,) or (1,)

Weights of the class prior: one per class at weight_level 3 and 4, a single one below.

feature_weights_list of ndarray

Weights of the conditional of every attribute, a list with one array per attribute, of shape (n_keys, n_classes) at weight_level 3 and 4 and (n_keys, 1) below.

n_iter_int

Number of L-BFGS-B iterations.

See also

TAN

The generative model.

WeightedKDB

The same weighting on a KDB network.

WeightedAnDE

Factor weights inside the SPnDEs of an AnDE ensemble.

References

[1] (1,2,3,4)

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]

Friedman, N., Geiger, D., & Goldszmidt, M. (1997). Bayesian network classifiers. Machine Learning, 29(2-3), 131-163.

Examples

>>> import numpy as np
>>> from sklearn.metrics import log_loss
>>> from skbn import TAN, WeightedTAN
>>> rng = np.random.RandomState(0)
>>> y = rng.randint(0, 2, size=300)
>>> x = rng.normal(size=300) + y
>>> X = np.column_stack([x, x, x, rng.normal(size=300) + y])  # x three times
>>> clf = WeightedTAN(weight_level=1).fit(X, y)
>>> clf.n_weights_  # the class prior, four attributes and the unseen key
6
>>> clf.learned_weights_.round(1)  # the copies of x count less
array([1. , 1.1, 0.3, 0.3, 1. , 1. ])
>>> tan = TAN().fit(X, y)
>>> bool(log_loss(y, clf.predict_proba(X)) < log_loss(y, tan.predict_proba(X)))
True

Methods

conditional_table(feature[, as_frame])

Return the conditional distribution of an attribute in the network.

fit(X, y[, sample_weight])

Fit the network, 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.

to_dot([feature_names, class_name])

Return the network in the DOT language of Graphviz.

weight_table(feature[, as_frame])

Return the weights of the conditional of an attribute with the combinations they belong to.

conditional_table(feature, as_frame=False)#

Return the conditional distribution of an attribute in the network.

The table has a row for every state of the class and of the parents of the attribute that occurs in training, with the probability of each value of the attribute, or the mean and the variance of its Gaussian. The states that do not occur have no row: there the model uses the uninformed estimate described in the class docstring.

Parameters:
featureint or str

The attribute, by its index or by its name in feature_names_in_.

as_framebool, default=False

If True, return a pandas DataFrame indexed by the class and the values of the parents, with a column per value of the attribute (or the columns mean and var).

Returns:
tableBunch or DataFrame

With as_frame=False, a dictionary-like object with:

featureint

Index of the attribute.

parentslist of int

Its parents among the attributes.

classesndarray of shape (n_states,)

Class of every row.

parent_valuesndarray of shape (n_states, n_parents)

Values of the parents in every row: their categories, or the index of the bin of a continuous parent (see cut_points_).

countndarray of shape (n_states,)

Number of training samples in the state of every row.

feature_valuesndarray of shape (n_values,) or None

Values of a discrete attribute: its categories, or False and True for a Bernoulli attribute (above its threshold or not).

probandarray of shape (n_states, n_values) or None

Probability of every value in every row.

mean, varndarray of shape (n_states,) or None

Mean and variance of a Gaussian attribute in every row.

Examples

>>> import numpy as np
>>> from skbn import KDB
>>> X = np.array([[0, 0], [0, 1], [1, 0], [1, 1]] * 5)
>>> y = np.array([0, 1, 1, 0] * 5)
>>> table = KDB(k=1).fit(X, y).conditional_table(1)
>>> table.parents, table.classes.tolist(), table.parent_values.ravel().tolist()
([0], [0, 0, 1, 1], [0, 1, 0, 1])
>>> table.proba.round(2)
array([[0.86, 0.14],
       [0.14, 0.86],
       [0.14, 0.86],
       [0.86, 0.14]])
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 edges_#

Arcs between attributes, as (parent, child) pairs of feature indices in the order of the children. Every attribute also has the class as a parent, which the pairs leave out.

property feature_types_#

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

property feature_weights_#

Weights of the conditional of every attribute, a list with one array per attribute, of shape (n_keys, n_classes) at weight_level 3 and 4 and (n_keys, 1) below. The rows are the combinations that the level tells apart (values of the attribute, with its parents at level 4) seen in training, a single row at level 1. An attribute the model ignores has no rows.

fit(X, y, sample_weight=None)#

Fit the network, then learn the discriminative weights.

Learns the structure and counts the conditional probability tables as the unweighted model does, then optimizes the weights 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. 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:
Carray-like of shape (n_samples, n_classes)

Returns the log-probability of the samples for each class.

predict_proba(X)#

Return probability estimates for the test vector X.

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

The input samples.

Returns:
Carray-like of shape (n_samples, n_classes)

Returns the probability of the samples for each class.

property prior_weights_#

Weights of the class prior: one per class at weight_level 3 and 4, a single one below.

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

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

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.

to_dot(feature_names=None, class_name='class')#

Return the network in the DOT language of Graphviz.

The text can be rendered with Graphviz or read by the libraries that take DOT, such as networkx and pydot. The attributes the model ignores (constant in training) are left out.

Parameters:
feature_namesarray-like of str of shape (n_features,), default=None

Names of the attributes. By default feature_names_in_, or x0, x1, … when the model was fitted without names.

class_namestr, default=”class”

Name of the class node.

Returns:
dotstr

A digraph with an arc from the class to every attribute and the arcs of edges_.

weight_table(feature, as_frame=False)#

Return the weights of the conditional of an attribute with the combinations they belong to.

weight_level decides what a weight is shared by: the whole conditional (level 1, a single row), each value of the attribute (2 and 3), or each value with each state of the parents (4); from level 3 on there is a column per class. A Gaussian attribute has no values to tell apart, so its rows are the states of its parents alone. Only the combinations that occur in training have a weight.

Parameters:
featureint or str

The attribute, by its index or by its name in feature_names_in_.

as_framebool, default=False

If True, return a pandas DataFrame indexed by the value of the attribute and the values of its parents, with a column per class (or a single column weight).

Returns:
tableBunch or DataFrame

With as_frame=False, a dictionary-like object with:

featureint

Index of the attribute.

weightsndarray of shape (n_rows, n_classes) or (n_rows, 1)

The weights, feature_weights_[feature].

feature_valuesndarray of shape (n_rows,) or None

Value of the attribute in every row, when the level tells the values apart.

parentslist of int

Parents of the attribute, when the level tells their states apart (empty otherwise).

parent_valuesndarray of shape (n_rows, n_parents)

Values of those parents in every row.

classesndarray of shape (n_classes,) or None

Class of every column, when there is one per class.

Examples using skbn.WeightedTAN#

Tutorial: from a table of labels to a fitted network

Tutorial: from a table of labels to a fitted network

Weighted TAN and KDB on duplicated attributes

Weighted TAN and KDB on duplicated attributes

A table of continuous measurements: what to expect

A table of continuous measurements: what to expect