ALR#
- class skbn.ALR(n_join=2, n_bins=5, strategy='quantile', alpha=1.0, categorical_features=None, bernoulli_features=None, gaussian_features=None, weight_level=3, l2_reg=0.0, max_iter=10000, tol=np.float64(2.220446049250313e-09), n_jobs=None)#
Accelerated Higher-Order Logistic Regression (ALR^n) [Hybrid].
The model of Zaidi et al. [1] (Eq. 13): every n-join probability of the AnJE gets a weight, learned by maximising the conditional log-likelihood,
\[\log P(y | x) = w_y \log P(y) + \sum_{\alpha \in \binom{A}{n}} w_{y, \alpha, x_\alpha} \log P(x_\alpha | y) - \log Z(x).\]The objective is convex. Weights start at 1 and are optimized with L-BFGS-B. The defaults reproduce the settings of the code of the original experiments [1] [2]: no penalty, 5 L-BFGS-B corrections, no stopping test on the projected gradient (its tolerance is 1e-33), and the optimizer stops when the relative reduction of the objective falls below 1e7 machine epsilons (L-BFGS-B’s
factr = 1e7) or after 10^4 iterations.l2_regadds the penalty towards 1 (the generative estimates) that [1] suggests for small datasets but does not evaluate.weight_level=3is the ALR^n of the paper. Levels 1 and 2 tie the weights across classes and values, following the nested parameterizations of Zaidi et al. [2] (Sec. 5.4), which the ALR paper does not use:Level
One weight per
1
n-join \(\alpha\)
2
n-join and value \((\alpha, x_\alpha)\)
3
n-join, value and class (ALR^n)
The class prior is weighted like an n-join with a single value. Only the cells observed in training get their own weight at levels 2 and 3; the unseen cells of an n-join share one weight that is never trained and keeps its value of 1, so the number of weights is bounded by the data.
- Parameters:
- n_joinint, default=2
Size
nof the attribute subsets (at least 1; ALR2 uses pairs). With fewer attributes thann_join, the single join of all attributes is used.- n_binsint, default=5
Number of bins for continuous attributes (at least 2).
- strategy{‘uniform’, ‘quantile’, ‘kmeans’, ‘mdlp’}, default=’quantile’
Binning strategy for 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
Weight
mof the m-estimates; must be positive.- categorical_featuresarray-like of int or bool, default=None
Indices (or a boolean mask) of the attributes to treat as discrete regardless of their dtype.
- bernoulli_featuresarray-like of int or bool, default=None
Indices (or a boolean mask) of the attributes to treat as discrete regardless of their dtype.
- gaussian_featuresarray-like of int or bool, default=None
Indices (or a boolean mask) of the attributes to treat as continuous (binned) regardless of their dtype. The attributes in none of the three parameters are typed from their training values with the rules of
MixedNB, and only those typed as Gaussian are binned. Columns of labels (strings, pandas categories) are discrete and cannot be declared continuous.- weight_levelint, default=3
Granularity of the weights, 1, 2 or 3 (see the table above).
- 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).- n_jobsint, default=None
Number of threads used to count the n-joins and to evaluate the objective.
Nonemeans 1 unless in ajoblib.parallel_backendcontext.-1means using all processors.
- Attributes:
- classes_ndarray of shape (n_classes,)
Class labels.
- 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.- joins_ndarray of shape (n_joins, n)
Attribute subsets of the n-joins, one row per subset, with
n = min(n_join, n_features_in_).- learned_weights_ndarray of shape (n_weights,)
Learned weights, one row per weight group and, at level 3, one column per class, flattened in row-major order.
- n_weights_int
Number of weights.
- n_iter_int
Number of L-BFGS-B iterations.
See also
AnJEThe generative model on the same n-joins.
w = 1is the unaveraged product of the n-joins, not the AnJE.GaussianALRALR^n on the factors of the SPnDEs, with Gaussian children.
WeightedAnDEDiscriminative weights on the AnDE ensemble.
References
Examples
>>> import numpy as np >>> from skbn import ALR >>> rng = np.random.RandomState(0) >>> x0 = rng.randint(0, 2, size=200) >>> x1 = rng.randint(0, 2, size=200) >>> x2 = rng.randint(0, 3, size=200) # noise >>> y = x0 ^ x1 # exclusive or: no attribute is informative on its own >>> X = np.column_stack([x0, x1, x2]) >>> clf = ALR(n_join=2).fit(X, y) >>> clf.score(X, y) 1.0
Methods
fit(X, y[, sample_weight])Fit the AnJE tables, 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([join, as_frame])Return the learned weights of an n-join (or of all n-joins at
weight_level=1) with the attribute values they belong to.- property cut_points_#
Cut-points of the continuous attributes that the model bins, and None for the discrete attributes.
- fit(X, y, sample_weight=None)#
Fit the AnJE tables, 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 n-joins.
- 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_.
- 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$') ALR#
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$') ALR#
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(join=None, as_frame=False)#
Return the learned weights of an n-join (or of all n-joins at
weight_level=1) with the attribute values they belong to.- Parameters:
- joinint, tuple or None, default=None
Index of the n-join in
joins_or tuple of its feature indices or names. Withweight_level=1,Nonereturns one row per n-join.- as_framebool, default=False
If True, return a pandas DataFrame.
- Returns:
- table
Bunchor DataFrame Dictionary-like object holding the decoded weights and labels.
- table
Examples using skbn.ALR#
Tutorial: from a table of labels to a fitted network
AnJE or ALR: generative and discriminative n-joins
A table of continuous measurements: what to expect