PivotTransformer#

class PivotTransformer(ml_task='clf', distance_measure='euclidean', k=None, reg_contrast_lambda=0.2, reg_max_thresholds=None, tree_params=None, standardize=True, embedder=None)[source]#

Bases: RuleTreeBaseTransformer

Transformer into the distances from candidate pivots, instances of the node that describe a class (medoids) or separate the classes.

Time series and images are flattened into one feature per value, so a tree can have pivot stumps on each of its data types (e.g. with base_stumps as tuples with the data types of each stump). The candidates are selected among the instances of the node. The distances are computed on the numerical features and on the one-hot encoding of the categorical ones, all standardized (z-score) if standardize; the encoding, the scaler and the distance matrix of the whole data set are computed once and cached in the tree. After the splitter has chosen a column, only the chosen pivot is kept (select).

Parameters:
  • ml_task ({MODEL_TYPE_CLF, MODEL_TYPE_REG}, default=MODEL_TYPE_CLF) – Task of the stump, which determines how the pivots are selected.

  • distance_measure (str or callable, default='euclidean') – Distance between the instances, computed on the standardized features (numerical and one-hot encoded categorical): any metric of sklearn.metrics.pairwise_distances.

  • k (int, default=None) – Regression only: number of nearest and farthest instances used to measure how well a candidate pivot contrasts close and distant instances. None for the square root of the number of instances of the node (between 5 and n - 1).

  • reg_contrast_lambda (float, default=0.2) – Regression only: weight of the contrast with respect to the gain of the split when the descriptive pivot is selected.

  • reg_max_thresholds (int, default=None) – Regression only: maximum number of thresholds tested on the distances from each candidate pivot (quantiles). None for max(256, sqrt(n)).

  • tree_params (dict, default=None) – Parameters of the decision trees that select the discriminative pivots.

  • standardize (bool, default=True) – Whether the features (or the embeddings) are standardized (z-score) before the distances, so that each of them weighs the same.

  • embedder (transformer, default=None) – Transformer of the data into vectors (e.g. RuleTree.utils.embeddings.ImageEmbedder): the distances (distance_measure) are computed on the standardized embeddings; with it, also texts are supported. It must be pretrained or stateless: it is fitted without data (fit(None)), also when a saved tree is loaded. The embeddings of the whole data set are computed once and cached in the tree, and the ones of new data once per instance. If None, time series and images are flattened.

Variables:
  • numerical (list of int) – Numerical columns of the feature matrix.

  • categorical (list of int) – Categorical columns of the feature matrix.

  • candidates (numpy.ndarray of shape (n_candidates, n_encoded_features)) – The candidate pivots (only the chosen one after select), encoded and standardized.

  • candidate_names (numpy.ndarray of shape (n_candidates,)) – Indices of the candidate pivots in the training set.

  • candidate_labels (numpy.ndarray of shape (n_candidates,)) – Target of the candidate pivots (not saved by get_state).

  • pivots (dict) – Indices in the training set of the descriptives, discriminatives and candidates pivots of the node (all of them, also after select).

  • categories (list of list) – Values of each categorical feature in the whole data set, the columns of its one-hot encoding; a value not seen in training is encoded as all zeros.

  • scaler (StandardScaler or None) – Scaler of the encoded features, fitted on the whole data set; None if not standardize.

  • media (dict) – Index in the training set -> the training instance as given to fit (e.g. an image), for the pivots of the split, drawn by plot_tree(show_media=True). Set by select.

See also

PivotTreeStumpClassifier, PivotTreeStumpRegressor

Examples

>>> from sklearn.datasets import load_iris
>>> from RuleTree import RuleTreeClassifier
>>> from RuleTree.stumps.Stump import Stump
>>> from RuleTree.stumps.splitters import ClassificationSplitter
>>> from RuleTree.stumps.transformers import PivotTransformer
>>> X, y = load_iris(return_X_y=True)
>>> transformer = PivotTransformer().fit(X, y, context=None, node_id=None, cache=None)
>>> transformer.transform(X[:2]).shape  # distances from 6 candidate pivots
(2, 6)
>>> model = RuleTreeClassifier(max_depth=2, base_stumps=Stump(PivotTransformer(), ClassificationSplitter()))
>>> model = model.fit(X, y)
property supported_data_types#

Tabular data, time series and images (flattened, or through the embedder); texts with an embedder.

fit(X, y, idx=None, data_type=None, sample_weight=None, *, context, node_id, cache)[source]#

Select the candidate pivots of the node (see PivotSelection), on the standardized features. The encoding, the scaler and the distance matrix of the whole data set are taken from the cache.

Parameters:
  • X (numpy.ndarray) – Data of the transformer’s type, all the instances.

  • y (numpy.ndarray) – Target, all the instances.

  • idx (numpy.ndarray, default=None) – Indices of the instances in the node. If None, all the instances.

  • data_type (str, default=None) – Type of X, used as key of the cached values.

  • sample_weight (numpy.ndarray, default=None) – Sample weights, all the instances.

  • context (RuleTree or None) – Tree being built, 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)).

Returns:

self

Return type:

PivotTransformer

Raises:

NoSplitFoundWarning – If the data have no feature.

transform(X, context=None, node_id=None, cache=None)[source]#

Distances of the instances from the candidate pivots (from the chosen pivot, after select).

Parameters:
  • X (numpy.ndarray) – Data of the transformer’s type (time series and images are flattened).

  • context (RuleTree, default=None) – The tree, None outside a tree.

  • node_id (str, default=None) – Identifier of the node of the stump, None outside a tree.

  • cache (dict, default=None) – Cache of the tree, when called by it; None otherwise.

Returns:

X_transformed

Return type:

numpy.ndarray of shape (n_samples, n_candidates)

select(feature)[source]#

Keep only the chosen pivot.

Parameters:

feature (int) – Column chosen by the splitter.

Returns:

feature – Always 0: the distance from the only pivot kept.

Return type:

int

feature_id(feature)[source]#

Identifier of a candidate pivot: the index of the instance in the training set.

Parameters:

feature (int) – Column of the feature matrix.

Returns:

feature_id

Return type:

str

get_state()[source]#

Fitted state: the pivot, its index, the candidate pivots, the features, the categories and the scaler.

Returns:

state – JSON-friendly dictionary, restored by set_state.

Return type:

dict

set_state(state)[source]#

Restore the fitted state saved by get_state.

Parameters:

state (dict) – Dictionary created by get_state.

Returns:

self

Return type:

PivotTransformer