WeightedKDB#
- class skbn.WeightedKDB(k=1, 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 K-Dependence Bayesian classifier.
The weighted conditionally Bayesian network (wCCBN) of Zaidi et al. [1] on the structure and the conditionals of
KDB[2]: every parameter of the network gets an exponent weight,\[P^w(y \mid \mathbf{x}) \propto P(y)^{w_y} \prod_{i} P(x_i \mid y, \mathbf{x}_{\Pi(i)})^{ w_{i, x_i, y, \mathbf{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 ofKDBand stay fixed: the weights start at, and are regularized towards, the generative model (w = 1). The objective is convex in the weights. Withk=0the network is Naive Bayes and the model is the weighted Naive Bayes of [1].The weights correct what the generative fit gets wrong when the data break the independence assumptions of the network, for instance attributes that are correlated or duplicated beyond what
kparents explain: 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
WeightedAnDEwithweight_scope="factor"andmean="geometric"applied to the single network of KDB. A test instance in a parent state never seen in training gets the uninformed conditional ofKDB. The fit keeps the per-factor log-likelihoods of the training set in memory, about12 * n_samples * n_classes * (n_features + 1)bytes, and each evaluation of the objective costs as much.- Parameters:
- kint, default=1
Maximum number of attribute parents of every attribute, in addition to the class.
k=0gives Naive Bayes.fit()raises aValueErrorwhen the joint states of the class and the parents of an attribute (with the values of the attribute, atweight_level=4) exceed a 64-bit index, which calls for a smallerkor fewer bins.- 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 (seeMDLPDiscretizer), which chooses the number of bins of each attribute, son_binsis 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.
Nonemeans 1 and-1all 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
ConvergenceWarningis raised at the end offit()when L-BFGS-B stops atmax_iterbefore converging; increasemax_iterortolin 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 ofn_binsandstrategy. 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
Xhas feature names that are all strings.- mutual_info_ndarray of shape (n_features,)
Empirical mutual information \(I(A_i; C)\) (in nats) between every (discretized) attribute and the class.
- 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.
- feature_order_ndarray of shape (n_features,)
Attributes in the order in which they were added to the network (decreasing
mutual_info_).- parents_list of ndarray
parents_[i]holds the attribute parents of attributei, by decreasingconditional_mutual_info_; it is empty for the attributes that depend only on the class.edges_list of tuple of intArcs between attributes, as
(parent, child)pairs of feature indices in the order of the children.cut_points_list of ndarray or NoneCut-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_dictIndices 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 conditionals of the attributes without attribute parents 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_level3 and 4, a single one below.feature_weights_list of ndarrayWeights of the conditional of every attribute, a list with one array per attribute, of shape (n_keys, n_classes) at
weight_level3 and 4 and (n_keys, 1) below.- n_iter_int
Number of L-BFGS-B iterations.
See also
KDBThe generative model.
WeightedTANThe same weighting on a TAN network.
WeightedAnDEFactor weights inside the SPnDEs of an AnDE ensemble.
References
[1] (1,2,3,4,5)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]Sahami, M. (1996). Learning limited dependence Bayesian classifiers. In Proceedings of the Second International Conference on Knowledge Discovery and Data Mining (KDD-96), 335-338.
Examples
>>> import numpy as np >>> from sklearn.metrics import log_loss >>> from skbn import KDB, WeightedKDB >>> 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 = WeightedKDB(k=2, weight_level=1).fit(X, y) >>> [p.tolist() for p in clf.parents_] [[], [0], [0, 1], [0, 1]] >>> clf.learned_weights_.round(1) # the copies of x count less array([1. , 1.1, 0.3, 0.3, 1. , 1. ]) >>> kdb = KDB(k=2).fit(X, y) >>> bool(log_loss(y, clf.predict_proba(X)) < log_loss(y, kdb.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 of this object.
get_params([deep])Get parameters for this estimator.
predict(X)Perform classification on an array of test vectors X.
Return log-probability estimates for the test vector 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
fitmethod.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
scoremethod.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
meanandvar).
- Returns:
- table
Bunchor 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.
- table
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. Binbholds the values fromcut_points_[i][b - 1](included) tocut_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_level3 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 (
NaNor 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
MetadataRequestencapsulating 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_level3 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$') WeightedKDB#
Configure whether metadata should be requested to be passed to the
fitmethod.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(seesklearn.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 tofitif provided. The request is ignored if metadata is not provided.False: metadata is not requested and the meta-estimator will not pass it tofit.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_weightparameter infit.
- 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$') WeightedKDB#
Configure whether metadata should be requested to be passed to the
scoremethod.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(seesklearn.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 toscoreif provided. The request is ignored if metadata is not provided.False: metadata is not requested and the meta-estimator will not pass it toscore.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_weightparameter inscore.
- 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
networkxandpydot. 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_, orx0,x1, … when the model was fitted without names.- class_namestr, default=”class”
Name of the class node.
- Returns:
- dotstr
A
digraphwith an arc from the class to every attribute and the arcs ofedges_.
- weight_table(feature, as_frame=False)#
Return the weights of the conditional of an attribute with the combinations they belong to.
weight_leveldecides 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:
- table
Bunchor 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.
- table
Examples using skbn.WeightedKDB#
Tutorial: from a table of labels to a fitted network