RuleTree#
- class RuleTree(max_leaf_nodes, min_samples_split, max_depth, prune_useless_leaves, base_stumps, stump_selection, random_state, exceptions='raise')[source]#
Bases:
RuleTreeBase,ABCBase class of the RuleTree models.
A RuleTree is a binary decision tree built best-first: the nodes are split one at a time, in the order given by
queue_push, until a stopping criterion is met. Each split is a stump (seeRuleTree.base.RuleTreeBaseStump.RuleTreeBaseStump) chosen amongbase_stumps, so the same tree can mix different kinds of splits (thresholds on features, distances from pivots, shapelets, …) and different data types (tabular data, time series, images).The subclasses define the task:
RuleTreeClassifier,RuleTreeRegressor,RuleTreeClusterand its variants.- Parameters:
max_leaf_nodes (int, default=None) – Maximum number of leaves. If None, unlimited.
min_samples_split (int) – Minimum number of instances to split a node.
max_depth (int) – Maximum depth of the tree (the root has depth 0).
prune_useless_leaves (bool) – Whether to merge, after fit, the sibling leaves with the same prediction.
base_stumps (RuleTreeBaseStump or list) –
Stumps used to split the nodes. One of:
a stump;
a list of stumps, chosen with equal probability;
a list of tuples
(probability, stump)or(probability, stump, data_types), where the probabilities sum to 1 anddata_types(a data type or a list of data types, seeRuleTree.utils.define.DATA_INPUT_TYPES) restricts the data the stump is used on. By default, a stump is used on every data type it supports. The probability of a stump is split equally among its data types.
stump_selection ({'random', 'best'}) – How the stump of each node is chosen: at random according to the probabilities, or the one with the highest gain among all the stumps and data types.
random_state (int, RandomState instance or None) – Seed of the random choice of the stumps, also given to the stumps whose random_state is None (so that they do not break ties at random).
exceptions ({'raise', 'ignore'}, default='raise') – What to do when a stump raises an error: raise it, or make the node a leaf and warn.
- Variables:
root (RuleTreeNode) – Root of the fitted tree.
candidate_splits (list of tuple) – Pairs (stump, data type) usable on the training data, with their probability:
(probability, stump, data_type).cache (dict) – Values cached by the stumps during fit (see
get_cache()).
See also
RuleTreeClassifier,RuleTreeRegressor,RuleTreeClusterRuleTree.base.RuleTreeBaseStump.RuleTreeBaseStumpthe interface of the stumps.
- get_cache(namespace: str) dict[source]#
Dictionary where the stumps store values shared among the splits, e.g. embeddings of the whole data set. The cache is cleared at every
fit(), kept bypartial_fit(), and can be cleared manually withclear_cache().- Parameters:
namespace (str) – Name of the cache. Each transformer uses its
cache_namespace(): its class name and a hash of its hyperparameters, e.g.get_cache(transformer.cache_namespace())(the same for the stumps that implementfitwithout a transformer).- Returns:
cache – The cache of the namespace (created if missing).
- Return type:
- clear_cache()[source]#
Remove all the values cached by the stumps (see
get_cache()).
- fit(X: ndarray | None = None, y: ndarray | None = None, X_ts: ndarray | None = None, X_img: ndarray | None = None, X_txt: ndarray | None = None, sample_weight=None)[source]#
Fit the tree on the provided data, starting from an empty tree.
At least one of X, X_ts, X_img and X_txt must be given; all the inputs refer to the same instances. Each argument is a data type (see
RuleTree.utils.define.DATA_INPUT_TYPES): the stumps are used on the data types they support.- Parameters:
X (numpy.ndarray of shape (n_samples, n_features), default=None) – Tabular data.
y (numpy.ndarray of shape (n_samples,), default=None) – Target (None for clustering).
X_ts (numpy.ndarray of shape (n_samples, n_signals, length), default=None) – Time series.
X_img (numpy.ndarray of shape (n_samples, ...), default=None) – Images.
X_txt (array-like of shape (n_samples,), default=None) – Texts.
sample_weight (numpy.ndarray of shape (n_samples,), default=None) – Sample weights, passed to the stumps.
- Returns:
self – The fitted tree.
- Return type:
- Raises:
ValueError – If no input is given, the inputs have different numbers of instances, or no stump supports the provided data.
- partial_fit(X: ndarray | None = None, y: ndarray | None = None, X_ts: ndarray | None = None, X_img: ndarray | None = None, X_txt: ndarray | None = None, sample_weight=None)[source]#
Continue growing the fitted tree: the current leaves are split further using the provided data, within the limits of max_depth and max_leaf_nodes (e.g. after increasing them with set_params). The existing splits are not changed. If the tree is not fitted, this is
fit().The cache of the stumps (see
get_cache()) is kept: callclear_cache()first if the data differ from those used to fill it.- Parameters:
X (numpy.ndarray of shape (n_samples, n_features), default=None) – Tabular data.
y (numpy.ndarray of shape (n_samples,), default=None) – Target (None for clustering).
X_ts (numpy.ndarray of shape (n_samples, n_signals, length), default=None) – Time series.
X_img (numpy.ndarray of shape (n_samples, ...), default=None) – Images.
X_txt (array-like of shape (n_samples,), default=None) – Texts.
sample_weight (numpy.ndarray of shape (n_samples,), default=None) – Sample weights, passed to the stumps.
- Returns:
self – The fitted tree.
- Return type:
- make_split(data: dict, y: ndarray | None, idx: ndarray, sample_weight=None, node_id: str | None = None) RuleTreeBaseStump[source]#
Fit the split of a node, choosing among
candidate_splits_according tostump_selection: a random pair (stump, data type), or the pair with the highest gain (gain_).- Parameters:
data (dict) – Whole data set, as
{data_type: array}.y (numpy.ndarray or None) – Target of the whole data set.
idx (numpy.ndarray) – Indices of the instances in the node.
sample_weight (numpy.ndarray, default=None) – Sample weights of the whole data set.
node_id (str, default=None) – Identifier of the node, passed to the stumps.
- Returns:
stump – The fitted stump.
- Return type:
- Raises:
NoSplitFoundWarning – If no stump can split the node.
- is_split_useless(data: dict, idx: ndarray, labels: ndarray) bool[source]#
Whether a split is useless, i.e. all the instances go to the same child.
- Parameters:
data (dict) – Whole data set, as
{data_type: array}.idx (numpy.ndarray) – Indices of the instances in the node.
labels (numpy.ndarray) – Result of the split on idx (1 left, 2 right).
- Returns:
useless
- Return type:
- predict(X: ndarray = None, X_ts=None, X_img=None, X_txt=None)[source]#
Predict the output of each instance: the prediction of the leaf it reaches.
- Parameters:
X (numpy.ndarray of shape (n_samples, n_features), default=None) – Tabular data.
X_ts (numpy.ndarray of shape (n_samples, n_signals, length), default=None) – Time series.
X_img (numpy.ndarray of shape (n_samples, ...), default=None) – Images.
X_txt (array-like of shape (n_samples,), default=None) – Texts.
- Returns:
y_pred – Predicted classes, values or cluster labels.
- Return type:
numpy.ndarray of shape (n_samples,)
- apply(X: ndarray | None = None, X_ts=None, X_img=None, X_txt=None)[source]#
Leaf reached by each instance.
- Parameters:
X (numpy.ndarray of shape (n_samples, n_features), default=None) – Tabular data.
X_ts (numpy.ndarray of shape (n_samples, n_signals, length), default=None) – Time series.
X_img (numpy.ndarray of shape (n_samples, ...), default=None) – Images.
X_txt (array-like of shape (n_samples,), default=None) – Texts.
- Returns:
leaves – Identifier (node_id) of the leaf reached by each instance.
- Return type:
numpy.ndarray of shape (n_samples,)
- update_statistics(X: ndarray | None = None, y: ndarray | None = None, X_ts=None, X_img=None, X_txt=None)[source]#
Recompute the statistics of the nodes (predictions, probabilities, number of instances, …) and of their stumps on new data, without changing the splits. For classification,
classes_become the classes of y (e.g. to re-label the tree with a new target). A node reached by no instance predicts nan.- Parameters:
X (numpy.ndarray of shape (n_samples, n_features), default=None) – Tabular data.
y (numpy.ndarray of shape (n_samples,), default=None) – Target (None for clustering).
X_ts (numpy.ndarray of shape (n_samples, n_signals, length), default=None) – Time series.
X_img (numpy.ndarray of shape (n_samples, ...), default=None) – Images.
X_txt (array-like of shape (n_samples,), default=None) – Texts.
- get_rules(columns_names=None)[source]#
Rules of the tree, as a nested dictionary.
- Parameters:
columns_names (list of str, default=None) – Names of the tabular features, used in the rules instead of
X_<index>.- Returns:
rules – Rule of the root: the node statistics (
node_id,is_leaf,prediction, …), the rule of the split (textual_rule,not_textual_rule, …) and the rules of the children inleft_nodeandright_node(None for a leaf). Seeprint_rules().- Return type:
- make_leaf(node: RuleTreeNode) RuleTreeNode[source]#
Hook called when a node becomes a leaf. The default implementation does nothing.
- Parameters:
node (RuleTreeNode) – The new leaf.
- Returns:
node
- Return type:
- queue_pop()[source]#
Pop the next node to split from the queue.
- Returns:
idx (numpy.ndarray) – Indices of the instances reaching the node.
node (RuleTreeNode)
- check_additional_halting_condition(y, curr_idx: ndarray)[source]#
Additional condition to stop splitting a node, defined by the subclasses (e.g. a pure node for classification). The default implementation never stops.
- Parameters:
y (numpy.ndarray or None) – Target of the whole data set.
curr_idx (numpy.ndarray) – Indices of the instances in the node.
- Returns:
halt
- Return type:
- abstractmethod prepare_node(y: ndarray | None, idx: ndarray, node_id: str, node: RuleTreeNode | None = None) RuleTreeNode[source]#
Create a node (or update
node) with the statistics of the instancesidx: prediction, probabilities, number of instances.- Parameters:
y (numpy.ndarray or None) – Target of the whole data set.
idx (numpy.ndarray) – Indices of the instances reaching the node.
node_id (str) – Identifier of the node: its path from the root, e.g.
"Rlr".node (RuleTreeNode, default=None) – Existing node to update instead of creating a new one.
- Returns:
node
- Return type:
- queue_push(node: RuleTreeNode, idx: ndarray)[source]#
Push a node to split into the queue: the priority defines the order in which the tree grows. By default, the shallowest nodes first (breadth-first growth).
- Parameters:
node (RuleTreeNode) – The node.
idx (numpy.ndarray) – Indices of the instances reaching the node.
- local_interpretation(X, joint_contribution=False)[source]#
Contribution of each feature to the predictions, as in treeinterpreter: the value of an instance (its prediction, or its class probabilities for classification) is the value of the root (bias) plus, for each split along its path, the change of value attributed to the feature of the split.
- Parameters:
X (numpy.ndarray of shape (n_samples, n_features)) – Tabular data, split by stumps whose
feature_originalis a column.joint_contribution (bool, default=False) – If True, the change of value of each split is given to the set of the features used so far along the path.
- Returns:
prediction (numpy.ndarray of shape (n_samples,) or (n_samples, n_classes)) – Value of the leaf of each instance.
bias (numpy.ndarray of shape (n_samples,) or (n_samples, n_classes)) – Value of the root.
contributions (numpy.ndarray of shape (n_samples, n_features[, n_classes]) or list of dict) – Contribution of each feature, or, with joint_contribution, a dictionary (tuple of features -> contribution) for each instance.
- classmethod print_rules(rules: dict = None, digits=2, indent: int = 0)[source]#
Print rules as an indented list of conditions and outputs.
- Parameters:
rules (dict) – Rules returned by
get_rules().digits (int, default=2) – Number of decimals of the numerical outputs.
indent (int, default=0) – Indentation level of the root.
- to_dict(filename=None)[source]#
Dictionary representation of the fitted tree, from which
from_dict()rebuilds it.- Parameters:
filename (str or path-like, default=None) – If given, the dictionary is also saved to this file as JSON.
- Returns:
dictionary – JSON-friendly dictionary with the class of the tree, its parameters (
args, base stumps included), the classes for classification trees and the nodes. The values may be NumPy scalars: to write it withjson, usecls=RuleTree.utils.data_utils.json_numpy_encoder(as done withfilename). See Saving and loading trees.- Return type:
- Raises:
sklearn.exceptions.NotFittedError – If the tree is not fitted.
- export_graphviz(*, columns_names=None, class_names=None, scaler=None, float_precision=3, max_depth=None, node_ids=True, samples=True, filled=True, colors=None, wrap=None, show_media=False, filename: str | None = None)[source]#
Graphviz graph of the tree (requires graphviz and matplotlib), with the same boxes as
plot_tree: the id, rule and number of instances of each node, the leaves colored by prediction, the arrowstrue(to the left child) andfalse, and the media of the splits, e.g. the shapelets, drawn into PNG files of a temporary directory.- Parameters:
columns_names (list of str, default=None) – Names of the tabular features.
class_names (list of str, default=None) – Names of the classes, in the order of
classes_(classification trees).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 and of the predicted values.
max_depth (int, default=None) – Maximum depth drawn: the subtrees below are shown as
(...). If None, the whole tree.node_ids (bool, default=True) – Whether to show the id of each node.
samples (bool, default=True) – Whether to show the number of training instances of each node.
filled (bool, default=True) – Whether to color the leaves by class, cluster or predicted value.
colors (dict, default=None) – Colors replacing the ones of
RuleTree.utils.plotting.DEFAULT_COLORS, as inplot_tree.wrap (int, default=None) – Maximum number of characters per line of a rule, as in
plot_tree. If None, one line per rule.show_media (bool, default=False) – Whether to draw the training instances used by the splits, e.g. the pivots, as in
plot_tree. The shapelets are always drawn.filename (str, default=None) – If given, the graph is also rendered to this file (it requires the Graphviz programs).
- Returns:
graph – The graph:
graph.sourceis its DOT source, andgraph.renderdraws it.- Return type:
graphviz.Digraph
Examples
>>> from sklearn.datasets import load_iris >>> from RuleTree import RuleTreeClassifier >>> iris = load_iris() >>> model = RuleTreeClassifier(max_depth=2, random_state=0).fit(iris.data, iris.target) >>> graph = model.export_graphviz(columns_names=iris.feature_names, ... class_names=list(iris.target_names)) >>> graph.render("iris_tree", format="png")
- plot_tree(ax=None, *, columns_names=None, class_names=None, scaler=None, float_precision=3, max_depth=None, node_ids=True, samples=True, filled=True, fontsize=None, colors=None, wrap=None, show_media=False)[source]#
Draw the tree with matplotlib, as
sklearn.tree.plot_tree(requires matplotlib).Each internal node shows its id, its rule (for the shapelet and proximity stumps, also the shapelets; with
show_media, the training instances it uses, e.g. its pivots) and its number of training instances; each leaf its prediction. The left child of a node (arrow “true”) gets the instances for which the rule is true. Unlikeexport_graphviz, it needs neither the Graphviz programs nor files: the drawing is a matplotlib figure, shown in notebooks and saved withsavefig.- Parameters:
ax (matplotlib.axes.Axes, default=None) – Axes to draw on. If None, a new figure, sized on the number of leaves and the depth.
columns_names (list of str, default=None) – Names of the tabular features.
class_names (list of str, default=None) – Names of the classes, in the order of
classes_(classification trees).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 and of the predicted values.
max_depth (int, default=None) – Maximum depth drawn: the subtrees below are shown as
(...). If None, the whole tree.node_ids (bool, default=True) – Whether to show the id of each node.
samples (bool, default=True) – Whether to show the number of training instances of each node.
filled (bool, default=True) – Whether to color the leaves by class, cluster or predicted value.
fontsize (float, default=None) – Size of the text. If None, the largest size with which the boxes do not overlap.
colors (dict, default=None) – Colors replacing the ones of
RuleTree.utils.plotting.DEFAULT_COLORS(e.g. for a dark background):text,split,split_edge,leaf,leaf_edge,edge,classes(a list) andvalues(a colormap).wrap (int, default=None) – Maximum number of characters per line: longer rules are split before their comparison operator, then between words, so that the boxes of trees with long feature names are narrower. If None, one line per rule.
show_media (bool, default=False) – Whether to draw the training instances used by the splits, as given to
fit: the pivots of the pivot stumps on time series, images and texts, below the rule or, for the proximity pivot stumps, on the arrows of the children (the first pivot on the left arrow, the one of the instances closer to it). They are saved in the stumps, so a loaded tree draws them too. The shapelets are always drawn.
- Returns:
ax – The axes of the drawing. The box of each node is a text of
ax.textswhose gid is the id of the node.- Return type:
matplotlib.axes.Axes
Examples
>>> import matplotlib >>> matplotlib.use("Agg") >>> from sklearn.datasets import load_iris >>> from RuleTree import RuleTreeClassifier >>> iris = load_iris() >>> model = RuleTreeClassifier(max_depth=2, random_state=0).fit(iris.data, iris.target) >>> ax = model.plot_tree(columns_names=iris.feature_names, class_names=list(iris.target_names)) >>> [text.get_text().split("\n")[1] for text in ax.texts if text.get_gid() in ("R", "Rl")] ['petal width (cm) <= 0.8', 'class = setosa']
- get_predicates()[source]#
Internal nodes (the ones with a split) in depth-first order.
- Returns:
predicates – Node id -> RuleTreeNode.
- Return type:
- get_node_by_id(node_id)[source]#
Node with the given identifier.
- Parameters:
node_id (str) – Identifier of the node: its path from the root, e.g.
"Rlr".- Returns:
node – The node, or None if not in the tree.
- Return type:
RuleTreeNode or None