treeple.tree
.UnsupervisedObliqueDecisionTree#
- class treeple.tree.UnsupervisedObliqueDecisionTree(*, criterion='twomeans', splitter='best', max_depth=None, min_samples_split='sqrt', min_samples_leaf=1, min_weight_fraction_leaf=0, max_features=None, max_leaf_nodes=None, random_state=None, min_impurity_decrease=0, feature_combinations=1.5, clustering_func=None, clustering_func_args=None)[source]#
Unsupervised oblique decision tree.
- Parameters:
- criterion{“twomeans”, “fastbic”}, default=”twomeans”
The function to measure the quality of a split. Supported criteria are “twomeans” for the variance impurity and “fastbic” for the BIC criterion. If
UnsupervisedCriterion
instance is passed in, then the user must abide by the Cython internal API. See source code.- splitter{“best”, “random”}, default=”best”
The strategy used to choose the split at each node. Supported strategies are “best” to choose the best split and “random” to choose the best random split. If
UnsupervisedSplitter
instance is passed in, then the user must abide by the Cython internal API. See source code.- max_depth
int
, default=None The maximum depth of the tree. If None, then nodes are expanded until all leaves are pure or until all leaves contain less than min_samples_split samples.
- min_samples_split
int
orfloat
, default=2 The minimum number of samples required to split an internal node:
If int, then consider
min_samples_split
as the minimum number.If float, then
min_samples_split
is a fraction andceil(min_samples_split * n_samples)
are the minimum number of samples for each split.
- min_samples_leaf
int
orfloat
, default=1 The minimum number of samples required to be at a leaf node. A split point at any depth will only be considered if it leaves at least
min_samples_leaf
training samples in each of the left and right branches. This may have the effect of smoothing the model, especially in regression.If int, then consider
min_samples_leaf
as the minimum number.If float, then
min_samples_leaf
is a fraction andceil(min_samples_leaf * n_samples)
are the minimum number of samples for each node.
- min_weight_fraction_leaf
float
, default=0.0 The minimum weighted fraction of the sum total of weights (of all the input samples) required to be at a leaf node. Samples have equal weight when sample_weight is not provided.
- max_features
int
,float
or {“auto”, “sqrt”, “log2”}, default=None The number of features to consider when looking for the best split:
If int, then consider
max_features
features at each split.If float, then
max_features
is a fraction andmax(1, int(max_features * n_features_in_))
features are considered at each split.If “auto”, then
max_features=sqrt(n_features)
.If “sqrt”, then
max_features=sqrt(n_features)
.If “log2”, then
max_features=log2(n_features)
.If None, then
max_features=n_features
.
- max_leaf_nodes
int
, default=None Grow a tree with
max_leaf_nodes
in best-first fashion. Best nodes are defined as relative reduction in impurity. If None then unlimited number of leaf nodes.- random_state
int
,RandomState
instance orNone
, default=None Controls the randomness of the estimator. The features are always randomly permuted at each split, even if
splitter
is set to"best"
. Whenmax_features < n_features
, the algorithm will selectmax_features
at random at each split before finding the best split among them. But the best found split may vary across different runs, even ifmax_features=n_features
. That is the case, if the improvement of the criterion is identical for several splits and one split has to be selected at random. To obtain a deterministic behaviour during fitting,random_state
has to be fixed to an integer. See how scikit-learn definesrandom_state
for details.- min_impurity_decrease
float
, default=0.0 A node will be split if this split induces a decrease of the impurity greater than or equal to this value.
The weighted impurity decrease equation is the following:
N_t / N * (impurity - N_t_R / N_t * right_impurity - N_t_L / N_t * left_impurity)
where
N
is the total number of samples,N_t
is the number of samples at the current node,N_t_L
is the number of samples in the left child, andN_t_R
is the number of samples in the right child.N
,N_t
,N_t_R
andN_t_L
all refer to the weighted sum, ifsample_weight
is passed.- feature_combinations
float
, default=1.5 The number of features to combine on average at each split of the decision trees.
- clustering_func
callable()
Scikit-learn compatible clustering function to take the affinity matrix and return cluster labels. By default,
sklearn.cluster.AgglomerativeClustering
.- clustering_func_args
dict
Clustering function class keyword arguments. Passed to
clustering_func
.
- Attributes:
feature_importances_
Return the feature importances.
Methods
apply
(X[, check_input])Return the index of the leaf that each sample is predicted as.
Compute the similarity matrix of samples in X.
cost_complexity_pruning_path
(X, y[, ...])Compute the pruning path during Minimal Cost-Complexity Pruning.
decision_path
(X[, check_input])Return the decision path in the tree.
fit_predict
(X[, y])Perform clustering on
X
and returns cluster labels.fit_transform
(X[, y])Fit to data, then transform it.
Return the depth of the decision tree.
get_leaf_node_samples
(X[, check_input])For each datapoint x in X, get the training samples in the leaf node.
Get metadata routing of this object.
Return the number of leaves of the decision tree.
get_params
([deep])Get parameters for this estimator.
predict
(X[, check_input])Assign labels based on clustering the affinity matrix.
predict_quantiles
(X[, quantiles, method, ...])Predict class or regression value for X at given quantiles.
set_fit_request
(*[, check_input, sample_weight])Request metadata passed to the
fit
method.set_output
(*[, transform])Set output container.
set_params
(**params)Set the parameters of this estimator.
set_predict_request
(*[, check_input])Request metadata passed to the
predict
method.transform
(X)Transform X to a cluster-distance space.
fit
- apply(X, check_input=True)#
Return the index of the leaf that each sample is predicted as.
New in version 0.17.
- Parameters:
- X{array_like, sparse matrix} of shape (n_samples, n_features)
The input samples. Internally, it will be converted to
dtype=np.float32
and if a sparse matrix is provided to a sparsecsr_matrix
.- check_input
bool
, default=True Allow to bypass several input checking. Don’t use this parameter unless you know what you’re doing.
- Returns:
- X_leavesarray_like of shape (n_samples,)
For each datapoint x in X, return the index of the leaf x ends up in. Leaves are numbered within
[0; self.tree_.node_count)
, possibly with gaps in the numbering.
- compute_similarity_matrix(X)#
Compute the similarity matrix of samples in X.
- Parameters:
- Xarray_like of shape (n_samples, n_features)
The input data.
- Returns:
- sim_matrixarray_like of shape (n_samples, n_samples)
The similarity matrix among the samples.
- cost_complexity_pruning_path(X, y, sample_weight=None)#
Compute the pruning path during Minimal Cost-Complexity Pruning.
See Minimal Cost-Complexity Pruning for details on the pruning process.
- Parameters:
- X{array_like, sparse matrix} of shape (n_samples, n_features)
The training input samples. Internally, it will be converted to
dtype=np.float32
and if a sparse matrix is provided to a sparsecsc_matrix
.- yarray_like of shape (n_samples,) or (n_samples, n_outputs)
The target values (class labels) as integers or strings.
- sample_weightarray_like of shape (n_samples,), default=None
Sample weights. If None, then samples are equally weighted. Splits that would create child nodes with net zero or negative weight are ignored while searching for a split in each node. Splits are also ignored if they would result in any single class carrying a negative weight in either child node.
- Returns:
- ccp_path
Bunch
Dictionary-like object, with the following attributes.
- ccp_alphasndarray
Effective alphas of subtree during pruning.
- impuritiesndarray
Sum of the impurities of the subtree leaves for the corresponding alpha value in
ccp_alphas
.
- ccp_path
- decision_path(X, check_input=True)#
Return the decision path in the tree.
New in version 0.18.
- Parameters:
- X{array_like, sparse matrix} of shape (n_samples, n_features)
The input samples. Internally, it will be converted to
dtype=np.float32
and if a sparse matrix is provided to a sparsecsr_matrix
.- check_input
bool
, default=True Allow to bypass several input checking. Don’t use this parameter unless you know what you’re doing.
- Returns:
- indicatorsparse matrix of shape (n_samples, n_nodes)
Return a node indicator CSR matrix where non zero elements indicates that the samples goes through the nodes.
- fit_predict(X, y=None, **kwargs)#
Perform clustering on
X
and returns cluster labels.- Parameters:
- Xarray_like of shape (n_samples, n_features)
Input data.
- yIgnored
Not used, present for API consistency by convention.
- **kwargs
dict
Arguments to be passed to
fit
.New in version 1.4.
- Returns:
- labels
ndarray
of shape (n_samples,), dtype=np.int64 Cluster labels.
- labels
- fit_transform(X, y=None, **fit_params)#
Fit to data, then transform it.
Fits transformer to
X
andy
with optional parametersfit_params
and returns a transformed version ofX
.- Parameters:
- Xarray_like of shape (n_samples, n_features)
Input samples.
- yarray_like of shape (n_samples,) or (n_samples, n_outputs), default=None
Target values (None for unsupervised transformations).
- **fit_params
dict
Additional fit parameters.
- Returns:
- get_depth()#
Return the depth of the decision tree.
The depth of a tree is the maximum distance between the root and any leaf.
- Returns:
- self.tree_.max_depth
int
The maximum depth of the tree.
- self.tree_.max_depth
- get_leaf_node_samples(X, check_input=True)#
For each datapoint x in X, get the training samples in the leaf node.
- Parameters:
- Xarray_like of shape (n_samples, n_features)
Dataset to apply the forest to.
- check_input
bool
, default=True Allow to bypass several input checking.
- Returns:
- leaf_nodes_samplesa
list
of array_like of length (n_samples,) Each sample is represented by the indices of the training samples that reached the leaf node. The
n_leaf_node_samples
may vary between samples, since the number of samples that fall in a leaf node is variable. Each array has shape (n_leaf_node_samples, n_outputs).
- leaf_nodes_samplesa
- 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_n_leaves()#
Return the number of leaves of the decision tree.
- Returns:
- self.tree_.n_leaves
int
Number of leaves.
- self.tree_.n_leaves
- get_params(deep=True)#
Get parameters for this estimator.
- predict(X, check_input=True)#
Assign labels based on clustering the affinity matrix.
- Parameters:
- Xarray_like of shape (n_samples, n_features)
Array to cluster.
- check_input
bool
, optional Whether to validate input, by default True.
- Returns:
- labelsarray_like of shape (n_samples,)
The assigned labels for each sample.
- predict_quantiles(X, quantiles=0.5, method='nearest', check_input=True)#
Predict class or regression value for X at given quantiles.
- Parameters:
- X{array_like, sparse matrix} of shape (n_samples, n_features)
Input data.
- quantiles
float
, optional The quantiles at which to evaluate, by default 0.5 (median).
- method
str
, optional The method to interpolate, by default ‘linear’. Can be any keyword argument accepted by
numpy.quantile()
.- check_input
bool
, optional Whether or not to check input, by default True.
- Returns:
- predictionsarray_like of shape (n_samples, n_outputs,
len
(quantiles)) The predicted quantiles.
- predictionsarray_like of shape (n_samples, n_outputs,
- set_fit_request(*, check_input='$UNCHANGED$', sample_weight='$UNCHANGED$')#
Request metadata passed to the
fit
method.Note that this method is only relevant if
enable_metadata_routing=True
(seesklearn.set_config()
). Please see User Guide on how the routing mechanism works.The options for each parameter are:
True
: metadata is requested, and passed tofit
if 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.New in version 1.3.
Note
This method is only relevant if this estimator is used as a sub-estimator of a meta-estimator, e.g. used inside a
Pipeline
. Otherwise it has no effect.- Parameters:
- Returns:
- self
object
The updated object.
- self
- set_output(*, transform=None)#
Set output container.
See Introducing the set_output API for an example on how to use the API.
- Parameters:
- transform{“default”, “pandas”, “polars”}, default=None
Configure output of
transform
andfit_transform
."default"
: Default output format of a transformer"pandas"
: DataFrame output"polars"
: Polars outputNone
: Transform configuration is unchanged
New in version 1.4:
"polars"
option was added.
- Returns:
- selfestimator instance
Estimator instance.
- 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:
- **params
dict
Estimator parameters.
- **params
- Returns:
- selfestimator instance
Estimator instance.
- set_predict_request(*, check_input='$UNCHANGED$')#
Request metadata passed to the
predict
method.Note that this method is only relevant if
enable_metadata_routing=True
(seesklearn.set_config()
). Please see User Guide on how the routing mechanism works.The options for each parameter are:
True
: metadata is requested, and passed topredict
if provided. The request is ignored if metadata is not provided.False
: metadata is not requested and the meta-estimator will not pass it topredict
.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.New in version 1.3.
Note
This method is only relevant if this estimator is used as a sub-estimator of a meta-estimator, e.g. used inside a
Pipeline
. Otherwise it has no effect.
- transform(X)#
Transform X to a cluster-distance space.
In the new space, each dimension is the distance to the cluster centers. Note that even if X is sparse, the array returned by
transform
will typically be dense.- Parameters:
- X{array_like, sparse matrix} of shape (n_samples, n_features)
New data to transform.
- Returns:
- X_new
ndarray
of shape (n_samples, n_samples) X transformed in the new space.
- X_new
- property feature_importances_#
Return the feature importances.
The importance of a feature is computed as the (normalized) total reduction of the criterion brought by that feature. It is also known as the Gini importance.
Warning: impurity-based feature importances can be misleading for high cardinality features (many unique values). See
sklearn.inspection.permutation_importance()
as an alternative.- Returns:
- feature_importances_
ndarray
of shape (n_features,) Normalized total reduction of criteria by feature (Gini importance).
- feature_importances_