GaussianALR#

class skbn.GaussianALR(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', l2_reg=0.0, max_iter=10000, tol=np.float64(2.220446049250313e-09))#

ALR^n on the factors of the SPnDEs [Hybrid].

The ALR^n of Zaidi et al. [1] with joins of size n_dependence + 1, built on the factors of GaussianAnJE: every factor gets one weight per value, class and parent instantiation (the factor weights of WeightedAnDE at level 4), the weighted factors are pooled with the AnJE exponents, and the weights are learned by maximising the conditional log-likelihood,

\[\log P(y | x) = \log P(y) + \frac{1}{|M|} \sum_{P \in M} \Big[ r\, w_{y, x_P} \log P(x_P | y) + c \sum_{j \notin P} w_{j, x_j, y, x_P} \log P(x_j | y, x_P) \Big] - \log Z(x).\]

At w = 1 the model is GaussianAnJE. The objective is convex. On discrete data the model spans the same family as ALR with n_join=n_dependence + 1, logistic regression with (n+1)-way interactions, with a different parameterization of the weights. The defaults reproduce the L-BFGS-B settings of the code of the ALR^n experiments [1], as in ALR: no penalty, 5 corrections, no stopping test on the projected gradient, and a stop when the relative reduction of the objective falls below 1e7 machine epsilons or after 10^4 iterations. Only the combinations that occur in training get their own weight, as in WeightedAnDE.

Parameters:
n_dependenceint, default=1

Order n of the SPnDEs; the joins have n + 1 attributes. It must satisfy 0 <= n_dependence <= n_features; 0 gives Naive Bayes.

n_binsint, default=5

Number of bins of the continuous super-parents (at least 2).

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

Binning strategy of the continuous 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

Laplace smoothing of the discrete factors and of the augmented-state prior; must be positive.

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 attribute (see MixedNB).

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 of an augmented state never seen in training (see AnDE).

l2_regfloat, default=0.0

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

max_iterint, default=10000

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=2.22e-9

Stopping tolerance on the relative reduction of the objective, (f_k - f_{k+1}) / max(|f_k|, |f_{k+1}|, 1) <= tol; the default is 1e7 machine epsilons, as in the original code, and None uses SciPy’s default (the same value).

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 prior, the class-level conditionals and as the fallback when no SPnDE qualifies.

coef_theta_ndarray of shape (n_weights,)

Optimized parameters, equal to learned_weights_ since the weights are exponents.

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

Number of L-BFGS-B iterations.

See also

ALR

The ALR^n on discretized attributes, with the m-estimates of [1].

GaussianAnJE

The generative model at w = 1.

References

[1] (1,2,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 GaussianALR
>>> rng = np.random.RandomState(0)
>>> y = rng.randint(0, 2, size=200)
>>> x0 = rng.normal(size=200)
>>> x1 = x0 * (2 * y - 1) + rng.normal(scale=0.3, size=200)  # slope of class
>>> X = np.column_stack([x0, x1])
>>> clf = GaussianALR(l2_reg=1.0).fit(X, y)
>>> clf.score(X, y) > 0.85
True

Methods

fit(X, y[, sample_weight])

Fit the factors of the SPnDEs, then 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 factors of the SPnDEs, then the discriminative weights.

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

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

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.GaussianALR#

Gaussian children or discretized attributes

Gaussian children or discretized attributes