Source code for empulse.models.tree.cstree

from typing import Any, ClassVar, Literal, Self

import numpy as np
from numpy.typing import NDArray
from scipy.sparse import csr_matrix
from sklearn.tree import DecisionTreeClassifier
from sklearn.tree._tree import Tree
from sklearn.utils import Bunch
from sklearn.utils._param_validation import Hidden, StrOptions
from sklearn.utils.validation import check_is_fitted, validate_data

from ..._types import FloatArrayLike, FloatNDArray, IntArrayLike, IntNDArray, ParameterConstraint
from ...metrics import BaseMetric
from .._base.cost_sensitive import CostSensitiveClassifier
from ._impurity import CostImpurity, build_cost_criterion

TREE_PARAM_CONSTRAINTS = DecisionTreeClassifier._parameter_constraints.copy()
TREE_PARAM_CONSTRAINTS.pop('criterion')


[docs] class CSTreeClassifier(CostSensitiveClassifier): # type: ignore[misc] """ Cost-sensitive decision tree classifier. Trees are split based on a cost-sensitive impurity measure. Read more in the :ref:`User Guide <cstree>`. .. seealso:: :class:`~empulse.models.CSLogitClassifier` : Cost-sensitive logistic regression classifier. :class:`~empulse.models.CSBoostClassifier` : Cost-sensitive gradient boosting classifier. :class:`~empulse.models.CSForestClassifier` : Cost-sensitive random forest classifier. :class:`~empulse.models.CSBaggingClassifier` : Bags an ensemble of cost-sensitive trees. Parameters ---------- tp_cost : float or array-like, shape=(n_samples,), default=0.0 Cost of true positives. If ``float``, then all true positives have the same cost. If array-like, then it is the cost of each true positive classification. Is overwritten if another `tp_cost` is passed to the ``fit`` method. .. note:: It is not recommended to pass instance-dependent costs to the ``__init__`` method. Instead, pass them to the ``fit`` method. tn_cost : float or array-like, shape=(n_samples,), default=0.0 Cost of true negatives. If ``float``, then all true negatives have the same cost. If array-like, then it is the cost of each true negative classification. Is overwritten if another `tn_cost` is passed to the ``fit`` method. .. note:: It is not recommended to pass instance-dependent costs to the ``__init__`` method. Instead, pass them to the ``fit`` method. fn_cost : float or array-like, shape=(n_samples,), default=0.0 Cost of false negatives. If ``float``, then all false negatives have the same cost. If array-like, then it is the cost of each false negative classification. Is overwritten if another `fn_cost` is passed to the ``fit`` method. .. note:: It is not recommended to pass instance-dependent costs to the ``__init__`` method. Instead, pass them to the ``fit`` method. fp_cost : float or array-like, shape=(n_samples,), default=0.0 Cost of false positives. If ``float``, then all false positives have the same cost. If array-like, then it is the cost of each false positive classification. Is overwritten if another `fp_cost` is passed to the ``fit`` method. .. note:: It is not recommended to pass instance-dependent costs to the ``__init__`` method. Instead, pass them to the ``fit`` method. loss : :class:`~empulse.metrics.BaseMetric` or None, default=None The metric to measure the quality of a split. If None, the cost impurity is used. criterion : {"cost", "gini", "log_loss" or "entropy"}, default="cost" The function to measure the quality of a split. How the measure to estimate quality of a split is weighted. - If ``"cost"``: The metric is used normally, without extra weighting. - If ``"gini"``: The Gini impurity is used to weight the metric. - If ``"log_loss"`` or ``"entropy"``: The Shannon information gain is used to weight the metric. 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. max_depth : int or None, 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 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_leaf : int 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_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 {"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 "sqrt", then `max_features=sqrt(n_features)`. - If "log2", then `max_features=log2(n_features)`. - If None, then `max_features=n_features`. .. note:: The search for a split does not stop until at least one valid partition of the node samples is found, even if it requires to effectively inspect more than ``max_features`` features. random_state : int, 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 :term:`Sklearn Glossary <sklearn:random_state>` for details. 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. 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, 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. class_weight : dict or "balanced", default=None Weights associated with classes in the form ``{class_label: weight}``. If None, both classes are supposed to have weight one. The "balanced" mode uses the values of y to automatically adjust weights inversely proportional to class frequencies in the input data as ``n_samples / (n_classes * np.bincount(y))`` Note that these weights will be multiplied with sample_weight (passed through the fit method) if sample_weight is specified. ccp_alpha : non-negative float, default=0.0 Complexity parameter used for Minimal Cost-Complexity Pruning. The subtree with the largest cost complexity that is smaller than ``ccp_alpha`` will be chosen. By default, no pruning is performed. See :ref:`sklearn:minimal_cost_complexity_pruning` for details. See :ref:`sklearn:sphx_glr_auto_examples_tree_plot_cost_complexity_pruning.py` for an example of such pruning. monotonic_cst : array-like of int of shape (n_features), default=None Indicates the monotonicity constraint to enforce on each feature. - 1: monotonic increase - 0: no constraint - -1: monotonic decrease If monotonic_cst is None, no constraints are applied. Monotonicity constraints are not supported for classifications trained on data with missing values. The constraints hold over the probability of the positive class. Read more in the :ref:`Sklearn User Guide <sklearn:monotonic_cst_gbdt>`. Attributes ---------- estimator_ : :class:`~sklearn.tree.DecisionTreeClassifier` The underlying DecisionTreeClassifier estimator. classes_ : ndarray of shape (2,) The class labels. feature_importances_ : ndarray of shape (n_features,) The impurity-based feature importances. The higher, the more important the feature. 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 [1]_. Warning: impurity-based feature importances can be misleading for high cardinality features (many unique values). See :func:`sklearn.inspection.permutation_importance` as an alternative. max_features_ : int The inferred value of max_features. n_classes_ : int The number of classes. n_features_in_ : int Number of features seen during :term:`fit <sklearn:fit>`. feature_names_in_ : ndarray of shape (`n_features_in_`,) Names of features seen during :term:`fit <sklearn:fit>`. Defined only when `X` has feature names that are all strings. n_outputs_ : int The number of outputs when ``fit`` is performed. Always ``1`` for this binary classifier; kept for scikit-learn compatibility. tree_ : Tree instance The underlying Tree object. Please refer to ``help(sklearn.tree._tree.Tree)`` for attributes of Tree object and :ref:`sklearn:sphx_glr_auto_examples_tree_plot_unveil_tree_structure.py` for basic usage of these attributes. References ---------- .. [1] Correa Bahnsen, A., Aouada, D., & Ottersten, B. "Example-Dependent Cost-Sensitive Decision Trees", Expert Systems with Applications, 42(19), 6609–6619, 2015, http://doi.org/10.1016/j.eswa.2015.04.042 """ _parameter_constraints: ClassVar[ParameterConstraint] = { **TREE_PARAM_CONSTRAINTS, **CostSensitiveClassifier._parameter_constraints, 'criterion': [ StrOptions({'cost', 'log_loss', 'gini', 'entropy'}), Hidden(CostImpurity), ], } def __init__( self, *, tp_cost: FloatArrayLike | float = 0.0, tn_cost: FloatArrayLike | float = 0.0, fn_cost: FloatArrayLike | float = 0.0, fp_cost: FloatArrayLike | float = 0.0, loss: BaseMetric | None = None, criterion: Literal['cost', 'gini', 'entropy', 'log_loss'] = 'cost', splitter: Literal['best', 'random'] = 'best', max_depth: int | None = None, min_samples_split: float = 2, min_samples_leaf: float = 1, min_weight_fraction_leaf: float = 0.0, max_features: Literal['sqrt', 'log2'] | float | None = None, random_state: int | np.random.RandomState | None = None, max_leaf_nodes: int | None = None, min_impurity_decrease: float = 0.0, class_weight: dict[int, float] | Literal['balanced'] | None = None, ccp_alpha: float = 0.0, monotonic_cst: IntArrayLike | None = None, ): self.criterion = criterion self.splitter = splitter self.max_depth = max_depth self.min_samples_split = min_samples_split self.min_samples_leaf = min_samples_leaf self.min_weight_fraction_leaf = min_weight_fraction_leaf self.max_features = max_features self.random_state = random_state self.max_leaf_nodes = max_leaf_nodes self.min_impurity_decrease = min_impurity_decrease self.class_weight = class_weight self.ccp_alpha = ccp_alpha self.monotonic_cst = monotonic_cst super().__init__(tp_cost=tp_cost, tn_cost=tn_cost, fp_cost=fp_cost, fn_cost=fn_cost, loss=loss) @property def feature_importances_(self) -> FloatNDArray: """The feature importances.""" check_is_fitted(self) importances: FloatNDArray = self.estimator_.feature_importances_ return importances @property def max_features_(self) -> int: """The inferred value of max_features.""" check_is_fitted(self) max_features: int = self.estimator_.max_features_ return max_features @property def n_classes_(self) -> int: """The number of classes.""" check_is_fitted(self) n_classes: int = self.estimator_.n_classes_ return n_classes @property def n_outputs_(self) -> int: """The number of outputs when ``fit`` is performed.""" check_is_fitted(self) n_outputs: int = self.estimator_.n_outputs_ return n_outputs @property def tree_(self) -> Tree: """The underlying Tree object.""" check_is_fitted(self) return self.estimator_.tree_
[docs] def get_depth(self) -> int: """Return the depth of the decision tree.""" check_is_fitted(self) depth: int = self.estimator_.get_depth() return depth
[docs] def get_n_leaves(self) -> int: """Return the number of leaves of the decision tree.""" check_is_fitted(self) n_leaves: int = self.estimator_.get_n_leaves() return n_leaves
def _fit( self, X: FloatNDArray, y: IntArrayLike, loss: BaseMetric, **loss_params: Any, ) -> Self: """ Build an example-dependent cost-sensitive decision tree from the training set. Parameters ---------- X : array-like of shape (n_samples, n_features) The input samples. y : array-like of shape (n_samples,) Ground truth (correct) labels. loss : BaseMetric Loss to be optimized. **loss_params : dict Additional keyword arguments to pass to the loss function if using a custom loss function. Returns ------- self : object Returns self. """ fp_cost, fn_cost, tp_cost, tn_cost = loss._evaluate_costs(replace_stochastic=True, **loss_params) n_samples = X.shape[0] self.criterion_ = build_cost_criterion( self.criterion, tp_cost=tp_cost, tn_cost=tn_cost, fn_cost=fn_cost, fp_cost=fp_cost, n_samples=n_samples, ) self.estimator_ = DecisionTreeClassifier( criterion=self.criterion_, splitter=self.splitter, max_depth=self.max_depth, min_samples_split=self.min_samples_split, min_samples_leaf=self.min_samples_leaf, min_weight_fraction_leaf=self.min_weight_fraction_leaf, max_features=self.max_features, random_state=self.random_state, max_leaf_nodes=self.max_leaf_nodes, min_impurity_decrease=self.min_impurity_decrease, class_weight=self.class_weight, ccp_alpha=self.ccp_alpha, monotonic_cst=self.monotonic_cst, ) self.estimator_.fit(X, y) return self
[docs] def predict(self, X: FloatArrayLike, check_input: bool = True) -> NDArray[Any]: """ Predict class value for X. 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_input : bool, default=True Allow to bypass several input checking. Don't use this parameter unless you know what you're doing. Returns ------- y : array-like of shape (n_samples,) The predicted classes. """ check_is_fitted(self) X = validate_data(self, X, reset=False) y_pred: NDArray[Any] = self.estimator_.predict(X, check_input=check_input) return y_pred
[docs] def predict_proba(self, X: FloatArrayLike, check_input: bool = True) -> FloatNDArray: """ Predict class probabilities of the input samples X. The predicted class probability is the fraction of samples of the same class in a leaf. 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_input : bool, default=True Allow to bypass several input checking. Don't use this parameter unless you know what you're doing. Returns ------- proba : ndarray of shape (n_samples, n_classes) The class probabilities of the input samples. The order of the classes corresponds to that in the attribute :term:`classes_ <sklearn:classes_>`. """ check_is_fitted(self) X = validate_data(self, X, reset=False) y_proba: FloatNDArray = self.estimator_.predict_proba(X, check_input=check_input) return y_proba
[docs] def predict_log_proba(self, X: FloatArrayLike) -> FloatNDArray: """ Predict class log-probabilities of the input samples X. 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``. Returns ------- proba : ndarray of shape (n_samples, n_classes) The class log-probabilities of the input samples. The order of the classes corresponds to that in the attribute :term:`classes_ <sklearn:classes_>`. """ check_is_fitted(self) y_log_proba: FloatNDArray = self.estimator_.predict_log_proba(X) return y_log_proba
[docs] def apply(self, X: FloatArrayLike, check_input: bool = True) -> IntNDArray: """ Return the index of the leaf that each sample is predicted as. 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_input : bool, default=True Allow to bypass several input checking. Don't use this parameter unless you know what you're doing. Returns ------- X_leaves : ndarray 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. """ check_is_fitted(self) X_leaves: IntNDArray = self.estimator_.apply(X, check_input=check_input) return X_leaves
[docs] def cost_complexity_pruning_path( self, X: FloatArrayLike, y: IntArrayLike, sample_weight: FloatArrayLike | None = None ) -> Bunch: """ Compute the pruning path during Minimal Cost-Complexity Pruning. See :ref:`sklearn: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``. y : array-like of shape (n_samples,) or (n_samples, n_outputs) The target values (class labels) as integers or strings. sample_weight : array-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 : :class:`~sklearn.utils.Bunch` Dictionary-like object, with the following attributes. ccp_alphas : ndarray Effective alphas of subtree during pruning. impurities : ndarray Sum of the impurities of the subtree leaves for the corresponding alpha value in ``ccp_alphas``. """ return self.estimator_.cost_complexity_pruning_path(X, y, sample_weight=sample_weight)
[docs] def decision_path(self, X: FloatArrayLike, check_input: bool = True) -> csr_matrix: """ Return the decision path in the tree. 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_input : bool, default=True Allow to bypass several input checking. Don't use this parameter unless you know what you're doing. Returns ------- indicator : sparse 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. """ return self.estimator_.decision_path(X, check_input=check_input) # type: ignore[no-any-return]