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 ofGaussianAnJE: every factor gets one weight per value, class and parent instantiation (the factor weights ofWeightedAnDEat 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 = 1the model isGaussianAnJE. The objective is convex. On discrete data the model spans the same family asALRwithn_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 inALR: 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 inWeightedAnDE.- Parameters:
- n_dependenceint, default=1
Order
nof the SPnDEs; the joins haven + 1attributes. It must satisfy0 <= n_dependence <= n_features;0gives 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 (seeMDLPDiscretizer), which chooses the number of bins of each attribute, son_binsis 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.
Nonemeans 1 unless in ajoblib.parallel_backendcontext.-1means 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.
0behaves 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
ConvergenceWarningis raised at the end offit()when L-BFGS-B stops atmax_iterbefore converging; increasemax_iterortolin 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
Xhas feature names that are all strings.- ensemble_sequence of dict
The fitted SPnDEs of the generative phase, one per set of
n_dependencesuper-parents (a single one forn_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 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, 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
ALRThe ALR^n on discretized attributes, with the m-estimates of [1].
GaussianAnJEThe generative model at
w = 1.
References
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 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.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. 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 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_samplesis the number of samples andn_featuresis the number of features. 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:
- 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
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$') GaussianALR#
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.
- 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 (whencomponent=None). Withweight_scope="factor", returns the weights of the root factor (feature=None) or of a child attribute insidecomponent(which defaults to 0 whenn_dependence=0).- Parameters:
- componentint, str, tuple or None, default=None
Component index, parent feature name (for
n_dependence=1), or tuple of parent features. Withweight_scope="component",Nonereturns all components together.- featureint, str or None, default=None
Child attribute (for
weight_scope="factor"), by index or by name infeature_names_in_.Noneselects the root factor \(P(y, \mathbf{x}_P)\).- as_framebool, default=False
If True, return a pandas DataFrame.
- Returns:
- table
Bunchor DataFrame Dictionary-like object holding the decoded weights and labels.
- table