treeple.tree.UnsupervisedDecisionTree#

class treeple.tree.UnsupervisedDecisionTree(*, criterion='twomeans', splitter='best', max_depth=None, min_samples_split='sqrt', min_samples_leaf=1, min_weight_fraction_leaf=0.0, max_features=None, max_leaf_nodes=None, random_state=None, min_impurity_decrease=0.0, clustering_func=None, clustering_func_args=None)[source]#

Unsupervised 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_depthint, 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_splitint or float, 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 and ceil(min_samples_split * n_samples) are the minimum number of samples for each split.

min_samples_leafint or float, 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 and ceil(min_samples_leaf * n_samples) are the minimum number of samples for each node.

min_weight_fraction_leaffloat, 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_featuresint, 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 and max(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_nodesint, 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_stateint, RandomState instance or None, default=None

Controls the randomness of the estimator. The features are always randomly permuted at each split, even if splitter is set to "best". When max_features < n_features, the algorithm will select max_features at random at each split before finding the best split among them. But the best found split may vary across different runs, even if max_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 defines random_state for details.

min_impurity_decreasefloat, 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, and N_t_R is the number of samples in the right child.

N, N_t, N_t_R and N_t_L all refer to the weighted sum, if sample_weight is passed.

clustering_funccallable()

Scikit-learn compatible clustering function to take the affinity matrix and return cluster labels. By default, sklearn.cluster.AgglomerativeClustering.

clustering_func_argsdict

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_similarity_matrix(X)

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.

get_depth()

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()

Get metadata routing of this object.

get_n_leaves()

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

Notes

The “faster” BIC criterion enablescomputation of the split point evaluations in O(n) time given that the samples are sorted. This algorithm is described in [1] and [2] and enables fast variance computations for the twomeans and fastbic criteria.

References

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 sparse csr_matrix.

check_inputbool, 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 sparse csc_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_pathBunch

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.

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 sparse csr_matrix.

check_inputbool, 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.

**kwargsdict

Arguments to be passed to fit.

New in version 1.4.

Returns:
labelsndarray of shape (n_samples,), dtype=np.int64

Cluster labels.

fit_transform(X, y=None, **fit_params)#

Fit to data, then transform it.

Fits transformer to X and y with optional parameters fit_params and returns a transformed version of X.

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_paramsdict

Additional fit parameters.

Returns:
X_newndarray array of shape (n_samples, n_features_new)

Transformed array.

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_depthint

The maximum depth of the tree.

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_inputbool, 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).

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_leavesint

Number of leaves.

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, check_input=True)[source]#

Assign labels based on clustering the affinity matrix.

Parameters:
Xarray_like of shape (n_samples, n_features)

Array to cluster.

check_inputbool, 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.

quantilesfloat, optional

The quantiles at which to evaluate, by default 0.5 (median).

methodstr, optional

The method to interpolate, by default ‘linear’. Can be any keyword argument accepted by numpy.quantile().

check_inputbool, optional

Whether or not to check input, by default True.

Returns:
predictionsarray_like of shape (n_samples, n_outputs, len(quantiles))

The predicted quantiles.

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 (see sklearn.set_config()). Please see 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.

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:
check_inputstr, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED

Metadata routing for check_input parameter in fit.

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_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 and fit_transform.

  • "default": Default output format of a transformer

  • "pandas": DataFrame output

  • "polars": Polars output

  • None: 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:
**paramsdict

Estimator parameters.

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 (see sklearn.set_config()). Please see User Guide on how the routing mechanism works.

The options for each parameter are:

  • True: metadata is requested, and passed to predict 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 predict.

  • 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:
check_inputstr, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED

Metadata routing for check_input parameter in predict.

Returns:
selfobject

The updated object.

transform(X)[source]#

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_newndarray of shape (n_samples, n_samples)

X transformed in the new space.

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).