WeightedNB#

class skbn.WeightedNB(categorical_features=None, bernoulli_features=None, gaussian_features=None, var_smoothing=1e-09, alpha=1.0, var_prior_weight=0.0, weight_level=3, l2_reg=1.0, max_iter=1000, tol=1e-06)#

Weighted Mixed Naive Bayes classifier (WANBIA / wCCBN on Naive Bayes).

Extends MixedNB with discriminative exponent weights on the class prior and every attribute conditional, learned by maximising the conditional log-likelihood with L-BFGS-B:

\[\log P^w(y \mid \mathbf{x}) = w_y \log P(y) + \sum_{i} w_{i, x_i, y} \log P(x_i \mid y) - \log Z(\mathbf{x}).\]

The objective is convex. The weights start at, and are regularized towards (l2_reg), the generative model w = 1, which predicts as MixedNB. weight_level=1 gives one weight per factor (WANBIA-C [1]), weight_level=2 one weight per factor and discrete value, and weight_level=3 (default) one weight per factor, discrete value and class (the weighted CCBN of Zaidi et al. [2] on the Naive Bayes structure).

Parameters:
categorical_featuresarray-like of int or bool, default=None

Indices (or a boolean mask) of the features to treat as categorical.

bernoulli_featuresarray-like of int or bool, default=None

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

gaussian_featuresarray-like of int or bool, default=None

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

var_smoothingfloat, default=1e-9

Non-negative portion of the largest variance of all Gaussian features added to variances for calculation stability.

alphafloat, default=1.0

Non-negative additive (Laplace/Lidstone) smoothing parameter.

var_prior_weightfloat, default=0.0

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

weight_levelint, default=3

Granularity of the weights, from 1 (one weight per factor: WANBIA-C) to 3 (one weight per factor, discrete value and class).

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

tolfloat or None, default=1e-6

Stopping tolerance of L-BFGS-B on the relative reduction of the objective and on the projected gradient.

Attributes:
classes_ndarray of shape (n_classes,)

Class labels known to the classifier.

class_log_prior_ndarray of shape (n_classes,)

Log of the empirical frequency 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.

feature_types_dict

Indices of the attributes of each type.

estimators_dict

Fitted Naive Bayes sub-estimators of the generative phase.

categories_list of ndarray

Sorted training values of each categorical feature.

bernoulli_thresholds_ndarray of shape (n_bernoulli_features,)

Binarisation threshold of each Bernoulli feature.

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, a single one below.

feature_weights_list of ndarray

Weights of the conditional of every attribute, a list with one array per attribute.

n_iter_int

Number of L-BFGS-B iterations.

See also

MixedNB

The generative model.

WeightedTAN

Discriminative weights on a TAN network.

WeightedKDB

Discriminative weights on a KDB network.

References

[1]

Zaidi, N. A., Cerquides, J., Carman, M. J., & Webb, G. I. (2013). Alleviating naive Bayes attribute independence assumption by attribute weighting. Journal of Machine Learning Research, 14, 1947-1988.

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

Examples

>>> import numpy as np
>>> from sklearn.metrics import log_loss
>>> from skbn import MixedNB, WeightedNB
>>> 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])
>>> clf = WeightedNB(weight_level=1).fit(X, y)
>>> nb = MixedNB().fit(X, y)
>>> bool(log_loss(y, clf.predict_proba(X)) < log_loss(y, nb.predict_proba(X)))
True

Methods

conditional_table(feature[, as_frame])

Return the class-conditional distribution of an attribute.

fit(X, y[, sample_weight])

Fit Naive Bayes, then learn the discriminative exponent 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 Naive Bayes network in Graphviz DOT format.

weight_table(feature[, as_frame])

Return the weights of an attribute with the values they belong to.

conditional_table(feature, as_frame=False)#

Return the class-conditional distribution of an attribute.

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, with a column per value of the attribute (or mean and var for a Gaussian attribute).

Returns:
tableBunch or DataFrame

With as_frame=False, a dictionary-like object with the same fields as TAN.conditional_table() and KDB.conditional_table(): feature, parents (empty), classes, parent_values (empty), count, feature_values, proba, mean and var.

property edges_#

Arcs between attributes: always empty for Naive Bayes.

property feature_weights_#

Weights of the conditional of every attribute, a list with one array per attribute.

fit(X, y, sample_weight=None)#

Fit Naive Bayes, then learn the discriminative exponent weights.

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

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

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 Naive Bayes network in Graphviz DOT format.

Parameters:
feature_namessequence of str, default=None

Names of the attributes. Defaults to feature_names_in_ when fitted on a DataFrame, otherwise x0, x1, …

class_namestr, default=”class”

Label of the class node.

Returns:
dotstr

A digraph with an arc from the class to every active attribute.

weight_table(feature, as_frame=False)#

Return the weights of an attribute with the values they belong to.

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 (when weight_level >= 2 and the attribute is discrete), with a column per class (or weight).

Returns:
tableBunch or DataFrame

With as_frame=False, a dictionary-like object with the same fields as WeightedTAN.weight_table(): feature, weights, feature_values, parents (empty), parent_values (empty) and classes.