Source code for RuleTree.base.RuleTreeBaseStump

"""Abstract base class of the stumps: the single splits that make up the nodes of a RuleTree."""

import hashlib
import json
from abc import ABC, abstractmethod
from typing import Optional

import numpy as np
from sklearn.base import BaseEstimator, TransformerMixin

from RuleTree.utils.define import DATA_TYPE_TABULAR


[docs] class RuleTreeBaseStump(BaseEstimator, ABC): """ Abstract base class of the stumps, the splits of the nodes of a RuleTree. A stump divides the instances of a node into two children: ``apply`` returns 1 for the instances that go to the left child and 2 for the ones that go to the right child. Notes ----- Stumps receive the whole data set as a dictionary ``data = {data_type: array}`` (see :data:`RuleTree.utils.define.DATA_INPUT_TYPES`) together with ``idx``, the indices of the instances reaching the node. A fitted stump works on a single data type, chosen by the tree among ``supported_data_types`` and stored in ``data_type_``. For convenience, ``data`` can also be a single array, interpreted as data of the stump's data type. The tree passes its cache to every stump, transformer and splitter (``cache``, a dictionary namespace -> dictionary of values that lives until the next ``fit`` or ``clear_cache()``), where they can store anything that can be shared among splits, e.g. embeddings computed on the whole data set. The code of each component decides whether and how to use it: the ones of the library keep their values under their own namespace, ``self._get_cache(cache)`` (:meth:`cache_namespace`: the class and the hyperparameters). Everything needed by ``apply`` must be stored in the stump itself. The tree also passes ``node_id``, the identifier of the node being split (``"R"``, ``"Rl"``, ...): with ``context.get_node_by_id(node_id)`` the stump reaches the node, and from it its ancestors and their stumps. The node is a leaf while its stump is fitted; its ancestors are already split. ``context``, ``node_id`` and ``cache`` are required in ``fit`` and ``update_statistics`` (None outside a tree), optional in ``apply``. Subclasses that work on a 2D matrix can implement ``_transform`` (data of the stump's data type -> matrix) and ``_apply_matrix`` (matrix -> 1/2 labels) and reuse :meth:`apply` and :meth:`update_statistics`. The stumps of the library are made of a transformer and a splitter (see :class:`RuleTree.stumps.Stump.Stump`), which is the simplest way to write a new stump. Attributes ---------- supported_data_types : tuple of str Data types the stump can be fitted on. task : str Kind of target, MODEL_TYPE_CLF (classification) or MODEL_TYPE_REG (regression). data_type_ : str Data type the stump has been fitted on. node_id_ : str or None Identifier of the node of the stump in its tree (set by ``fit`` and by RuleTreeNode.set_stump), None for a stump outside a tree. See Also -------- RuleTree.stumps.Stump.Stump : a stump made of a transformer and a splitter, the simplest way to write a new stump (see :doc:`/guides/extending`). """ supported_data_types = (DATA_TYPE_TABULAR,) # identifier of the node of the stump in its tree, None outside a tree node_id_ = None
[docs] @abstractmethod def fit(self, data, y, idx=None, data_type=None, sample_weight=None, check_input=True, *, context, node_id, cache): """ Fit the stump on the instances ``idx`` of ``data``. Parameters ---------- data : dict or numpy.ndarray Whole data set, as ``{data_type: array}``. y : numpy.ndarray Target of the whole data set. idx : numpy.ndarray, default=None Indices of the instances reaching the node. If None, all the instances. data_type : str, default=None Data type to use. If None, the first supported data type available in ``data``. sample_weight : numpy.ndarray, default=None Sample weights of the whole data set. check_input : bool, default=True Whether to check the input data. context : RuleTree or None Tree being built, None outside a tree: it holds the cache shared among the splits, and it is passed to the transformer and the splitter. node_id : str or None Identifier of the node being split, stored in ``node_id_``. None outside a tree. cache : dict or None Cache of the tree (namespace -> dictionary of values), None outside a tree: the component decides whether and how to use it (the ones of the library use ``self._get_cache(cache)``). Returns ------- self : RuleTreeBaseStump The fitted stump. Raises ------ NoSplitFoundWarning If the instances cannot be split. """ raise NotImplementedError("The fit method must be implemented in subclasses.")
[docs] @abstractmethod def get_rule(self, columns_names:list=None, scaler:TransformerMixin=None, float_precision: Optional[int] = 3) -> dict: """ Human-readable representation of the split. Parameters ---------- columns_names : list of str, default=None Names of the features, used instead of their indices. scaler : TransformerMixin, default=None Scaler used to preprocess the data: the thresholds are shown in the original scale. float_precision : int, default=3 Number of decimals of the thresholds. If None, they are not rounded. Returns ------- rule : dict The rule, with at least the keys ``textual_rule`` and ``not_textual_rule`` (the condition of the left child and its negation), ``blob_rule`` and ``not_blob_rule``. """ pass
[docs] def get_plot_rule(self, columns_names: list = None, scaler: TransformerMixin = None, float_precision: Optional[int] = 3) -> dict: """ What the node of the split shows in ``RuleTree.plot_tree``. The default implementation is the rule, ``get_rule(...)["textual_rule"]``; stumps that draw something in the node, such as the shapelet and pivot stumps, add their media (see below). Parameters ---------- columns_names : list of str, default=None Names of the tabular features. scaler : TransformerMixin, default=None Scaler used to preprocess the data: the thresholds are shown in the original scale. float_precision : int, default=3 Number of decimals of the threshold. Returns ------- rule : dict ``label``, the text of the node, and optionally its media: ``media_values``, values saved in the stump (e.g. the shapelets, or the pivots as given to fit), drawn as ``media_kind`` ('series', 'image' or 'text') with their ``media_names`` and ``media_colors``; only with ``show_media`` if ``media_optional``; below the rule or, if ``media_on_edges`` and they are two, on the arrows of the two children. """ return {"label": self.get_rule(columns_names=columns_names, scaler=scaler, float_precision=float_precision)["textual_rule"]}
[docs] @abstractmethod def node_to_dict(self) -> dict: """ Dictionary representation of the stump, used to save the tree (see RuleTree.to_dict). Returns ------- node_dict : dict JSON-friendly dictionary with the key ``stump_type`` (module of the stump class) and all that is needed by :meth:`dict_to_node` to rebuild the stump. """ raise NotImplementedError("The node_to_dict method must be implemented in subclasses.")
[docs] @classmethod @abstractmethod def dict_to_node(cls, node_dict: dict) -> 'RuleTreeBaseStump': """ Create a stump from a dictionary created by :meth:`node_to_dict`. Parameters ---------- node_dict : dict Dictionary representation of the stump. Returns ------- stump : RuleTreeBaseStump The stump, fitted if it was fitted when saved. """ raise NotImplementedError("The dict_to_node method must be implemented in subclasses.")
@property def task(self) -> str: """ Kind of target of the stump: MODEL_TYPE_CLF (classification) or MODEL_TYPE_REG (regression). A tree accepts only stumps of its task (see RuleTree._get_stumps_task). """ raise NotImplementedError(f"{self.__class__.__name__} must define its task.")
[docs] def supports(self, data_type:str) -> bool: """ Whether the stump can be fitted on a data type. Parameters ---------- data_type : str A data type, e.g. ``"tabular"`` (see :data:`RuleTree.utils.define.DATA_INPUT_TYPES`). Returns ------- supported : bool True if ``data_type`` is in ``supported_data_types``. """ return data_type in self.supported_data_types
[docs] def apply(self, data, idx=None, context=None, node_id=None, cache=None) -> np.ndarray: """ Apply the split to the instances ``idx`` of ``data``. Parameters ---------- data : dict or numpy.ndarray Data set, as ``{data_type: array}`` or a single array of the stump's data type. idx : numpy.ndarray, default=None Indices of the instances to split. If None, all the instances. context : RuleTree, default=None The tree, when called by it (fit, predictions); None otherwise. node_id : str, default=None Identifier of the node of the stump, when called by the tree; None otherwise. cache : dict, default=None Cache of the tree, when called by it; None otherwise. Returns ------- labels : numpy.ndarray of int For each instance in ``idx``, 1 if it goes to the left child, 2 otherwise. """ X = self._get_data(data) if idx is not None: X = X[idx] return self._apply_matrix(self._transform(X, context=context, node_id=node_id, cache=cache), context=context, node_id=node_id, cache=cache)
[docs] def update_statistics(self, data, y, idx=None, sample_weight=None, check_input=True, *, context, node_id, cache): """ Recompute the statistics of the split (e.g. impurity) on the instances ``idx`` of ``data``, without changing the split. Parameters ---------- data : dict or numpy.ndarray Whole data set, as ``{data_type: array}``. y : numpy.ndarray Target of the whole data set. idx : numpy.ndarray, default=None Indices of the instances reaching the node. If None, all the instances. sample_weight : numpy.ndarray, default=None Sample weights of the whole data set. check_input : bool, default=True Not used, kept for symmetry with :meth:`fit`. context : RuleTree or None The tree, None outside a tree. node_id : str or None Identifier of the node, None outside a tree. cache : dict or None Cache of the tree (namespace -> dictionary of values), None outside a tree: the component decides whether and how to use it (the ones of the library use ``self._get_cache(cache)``). """ if idx is None: idx = slice(None) X = self._transform(self._get_data(data)[idx], context=context, node_id=node_id, cache=cache) self._update_statistics_matrix(X, y[idx], None if sample_weight is None else sample_weight[idx], context=context, node_id=node_id, cache=cache)
def _transform(self, X: np.ndarray, context=None, node_id=None, cache=None) -> np.ndarray: """ Turn data of the stump's data type into the matrix the split is applied on. Parameters ---------- X : numpy.ndarray Data of the stump's data type. context : RuleTree, default=None The tree, when called by it (fit, predictions); None otherwise. node_id : str, default=None Identifier of the node of the stump, when called by the tree; None otherwise. cache : dict, default=None Cache of the tree, when called by it; None otherwise. Returns ------- X_transformed : numpy.ndarray of shape (n_samples, n_features) Feature matrix. The default implementation returns X. """ return X def _apply_matrix(self, X: np.ndarray, context=None, node_id=None, cache=None) -> np.ndarray: """ Apply the split to the matrix returned by :meth:`_transform`. Parameters ---------- X : numpy.ndarray of shape (n_samples, n_features) Feature matrix. context : RuleTree, default=None The tree, when called by it (fit, predictions); None otherwise. node_id : str, default=None Identifier of the node of the stump, when called by the tree; None otherwise. cache : dict, default=None Cache of the tree, when called by it; None otherwise. Returns ------- labels : numpy.ndarray of int 1 for the rows that go to the left child, 2 otherwise. """ raise NotImplementedError(f"{self.__class__.__name__} must implement apply or _apply_matrix.") def _update_statistics_matrix(self, X: np.ndarray, y: np.ndarray, sample_weight=None, *, context, node_id, cache): """ Recompute the split statistics on the matrix returned by :meth:`_transform`. Parameters ---------- X : numpy.ndarray of shape (n_samples, n_features) Feature matrix of the instances in the node. y : numpy.ndarray Target of the instances in the node. sample_weight : numpy.ndarray, default=None Sample weights of the instances in the node. context : RuleTree or None The tree, None outside a tree. node_id : str or None Identifier of the node, e.g. ``"Rl"`` (``context.get_node_by_id(node_id)``), None outside a tree. cache : dict or None Cache of the tree (namespace -> dictionary of values), None outside a tree: the component decides whether and how to use it (the ones of the library use ``self._get_cache(cache)``). """ def _resolve_fit_data(self, data, data_type=None) -> tuple[np.ndarray, str]: """Select the data to fit on and store its type in ``data_type_``.""" if not isinstance(data, dict): data = {data_type if data_type is not None else self.supported_data_types[0]: data} if data_type is None: available = [t for t in self.supported_data_types if t in data] if not available: raise ValueError(f"{self.__class__.__name__} supports {list(self.supported_data_types)} data, " f"got {list(data)}.") data_type = available[0] if not self.supports(data_type): raise ValueError(f"{self.__class__.__name__} does not support {data_type} data.") if data_type not in data: raise ValueError(f"No {data_type} data provided.") self.data_type_ = data_type return np.asarray(data[data_type]), data_type def _get_data(self, data) -> np.ndarray: """Data of the type the stump has been fitted on.""" return np.asarray(data[self.data_type_]) if isinstance(data, dict) else np.asarray(data)
[docs] def cache_namespace(self) -> str: """ Name of the cache of the stump in the tree (see RuleTree.get_cache): the class name and a hash of the hyperparameters, also of the components (e.g. the transformer of a Stump). Stumps of the same class with different hyperparameters do not share cached values. The tree gives its ``random_state`` to the stumps without one, so the namespace of a stump used by a tree is the one of its copy in ``candidate_splits_``. Returns ------- namespace : str E.g. ``"PivotTreeStumpClassifier-1a2b3c4d"``. Examples -------- >>> from RuleTree.stumps.classification import DecisionTreeStumpClassifier >>> a, b = DecisionTreeStumpClassifier(), DecisionTreeStumpClassifier(criterion="entropy") >>> a.cache_namespace().startswith("DecisionTreeStumpClassifier-") True >>> a.cache_namespace() == DecisionTreeStumpClassifier().cache_namespace() != b.cache_namespace() True """ return estimator_namespace(self)
def _get_cache(self, cache) -> dict: """ Values of the stump in the cache of the tree, under :meth:`cache_namespace`. Parameters ---------- cache : dict or None Cache of the tree, as received by ``fit`` (namespace -> dictionary of values). Returns ------- values : dict The cache of the stump; without a cache, an empty dictionary that is not kept. """ return cache.setdefault(self.cache_namespace(), {}) if cache is not None else {}
def rule_dict(condition: str, negation: str, **attributes) -> dict: """ Dictionary of a rule as returned by the ``get_rule`` of the stumps: the condition of the left child and its negation, as text (``textual_rule``, ``blob_rule``), after the given attributes of the split. Parameters ---------- condition : str Condition of the left child, e.g. ``"X_3 <= 0.8"``. negation : str Its negation, the condition of the right child, e.g. ``"X_3 > 0.8"``. **attributes : dict Other keys of the rule, e.g. ``feature_idx``, ``threshold``, ``is_categorical``, ``feature_name``. Returns ------- rule : dict Examples -------- >>> from RuleTree.base.RuleTreeBaseStump import rule_dict >>> rule = rule_dict("X_3 <= 0.8", "X_3 > 0.8", feature_idx=3, threshold=0.8) >>> rule["textual_rule"], rule["not_textual_rule"] ('X_3 <= 0.8', 'X_3 > 0.8') """ return attributes | { "textual_rule": condition, "blob_rule": condition, "not_textual_rule": negation, "not_blob_rule": negation, } def numerical_rule(feature_idx, feature_name: str, threshold, float_precision=3, **attributes) -> dict: """ Dictionary of a numerical rule, ``feature_name <= threshold`` (see rule_dict). Parameters ---------- feature_idx : object Identifier of the feature, stored in ``feature_idx``. feature_name : str Text of the feature in the rule, e.g. ``"X_3"`` or ``"P_12"``. threshold : float Threshold of the split. float_precision : int, default=3 Number of decimals of the threshold in the text; None for no rounding. **attributes : dict Other keys of the rule. Returns ------- rule : dict Examples -------- >>> from RuleTree.base.RuleTreeBaseStump import numerical_rule >>> numerical_rule(112, "P_112", 3.69187, float_precision=2)["not_textual_rule"] 'P_112 > 3.69' """ value = str(threshold) if float_precision is None else round(threshold, float_precision) return rule_dict(f"{feature_name} <= {value}", f"{feature_name} > {value}", feature_idx=feature_idx, threshold=threshold, is_categorical=False, feature_name=feature_name, **attributes) def estimator_namespace(estimator: BaseEstimator) -> str: """ Name of the cache of an estimator (a stump or a transformer) in a tree: its class name and a hash of its hyperparameters, also of its components. Parameters ---------- estimator : BaseEstimator The stump or the transformer. Returns ------- namespace : str E.g. ``"PivotTransformer-1a2b3c4d"``. """ params = {name: f"<{type(value).__module__}.{type(value).__qualname__}>" if hasattr(value, "get_params") else value # a component, e.g. an estimator for name, value in estimator.get_params(deep=True).items()} digest = hashlib.md5(json.dumps(params, sort_keys=True, default=repr).encode()).hexdigest() return f"{estimator.__class__.__name__}-{digest[:8]}"