# econml.policy.PolicyTree

class econml.policy.PolicyTree(*, criterion='neg_welfare', splitter='best', max_depth=None, min_samples_split=10, min_samples_leaf=5, min_weight_fraction_leaf=0.0, max_features=None, random_state=None, min_impurity_decrease=0.0, min_balancedness_tol=0.45, honest=True)[source]

Bases: econml._tree_exporter._SingleTreeExporterMixin, econml.tree._tree_classes.BaseTree

Welfare maximization policy tree. Trains a tree to maximize the objective: $$1/n \sum_i \sum_j a_j(X_i) * y_{ij}$$, where, where $$a(X)$$ is constrained to take value of 1 only on one coordinate and zero otherwise. This corresponds to a policy optimization problem.

Parameters
• criterion ({'neg_welfare'}, default=’neg_welfare’) – The criterion type

• splitter ({“best”}, default=”best”) – The strategy used to choose the split at each node. Supported strategies are “best” to choose the best split.

• max_depth (int, 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=10) – 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=5) – 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 {“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 int(max_features * n_features) features are considered at each split.

• If “auto”, then max_features=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.

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.

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

• min_balancedness_tol (float in [0, .5], default=.45) – How imbalanced a split we can tolerate. This enforces that each split leaves at least (.5 - min_balancedness_tol) fraction of samples on each side of the split; or fraction of the total weight of samples, when sample_weight is not None. Default value, ensures that at least 5% of the parent node weight falls in each side of the split. Set it to 0.0 for no balancedness and to .5 for perfectly balanced splits. For the formal inference theory to be valid, this has to be any positive constant bounded away from zero.

• honest (bool, default=True) – Whether the data should be split in two equally sized samples, such that the one half-sample is used to determine the optimal split at each node and the other sample is used to determine the value of every node.

feature_importances_

The feature importances based on the amount of parameter heterogeneity they create. The higher, the more important the feature.

Type

ndarray of shape (n_features,)

max_features_

The inferred value of max_features.

Type

int

n_features_in_

The number of features when fit is performed.

Type

int

n_samples_

The number of training samples when fit is performed.

Type

int

honest_

Whether honesty was enabled when fit was performed

Type

int

tree_

The underlying Tree object. Please refer to help(econml.tree._tree.Tree) for attributes of Tree object.

Type

Tree instance

policy_value_

The value achieved by the recommended policy

Type

float

always_treat_value_

The value of the policy that treats all samples

Type

float

__init__(*, criterion='neg_welfare', splitter='best', max_depth=None, min_samples_split=10, min_samples_leaf=5, min_weight_fraction_leaf=0.0, max_features=None, random_state=None, min_impurity_decrease=0.0, min_balancedness_tol=0.45, honest=True)[source]

Methods

 __init__(*[, criterion, splitter, ...]) apply(X[, check_input]) Return the index of the leaf that each sample is predicted as. decision_path(X[, check_input]) Return the decision path in the tree. export_graphviz([out_file, feature_names, ...]) Export a graphviz dot file representing the learned tree model feature_importances([max_depth, ...]) Parameters max_depth (int, default=4) -- Splits of depth larger than max_depth are not used in this calculation fit(X, y, *[, sample_weight, check_input]) Fit the tree from the data Return the depth of the decision tree. Return the number of leaves of the decision tree. get_params([deep]) Get parameters for this estimator. Regenerate the train_test_split of input sample indices that was used for the training and the evaluation split of the honest tree construction structure. init() plot([ax, title, feature_names, ...]) Exports policy trees to matplotlib predict(X[, check_input]) Predict the best treatment for each sample predict_proba(X[, check_input]) Predict the probability of recommending each treatment predict_value(X[, check_input]) Predict the expected value of each treatment for each sample render(out_file[, format, view, ...]) Render the tree to a flie set_params(**params) Set the parameters of this estimator.

Attributes

 feature_importances_ n_features_ node_dict_ tree_model_
apply(X, check_input=True)

Return the index of the leaf that each sample is predicted as.

Parameters
• X ({array-like} of shape (n_samples, n_features)) – The input samples. Internally, it will be converted to dtype=np.float64

• check_input (bool, default=True) – Allow to bypass several input checking. Don’t use this parameter unless you know what you do.

Returns

X_leaves – 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.

Return type

array-like of shape (n_samples,)

decision_path(X, check_input=True)

Return the decision path in the tree.

Parameters
• X ({array-like} of shape (n_samples, n_features)) – The input samples. Internally, it will be converted to dtype=np.float64

• check_input (bool, default=True) – Allow to bypass several input checking. Don’t use this parameter unless you know what you do.

Returns

indicator – Return a node indicator CSR matrix where non zero elements indicates that the samples goes through the nodes.

Return type

sparse matrix of shape (n_samples, n_nodes)

export_graphviz(out_file=None, feature_names=None, treatment_names=None, max_depth=None, filled=True, leaves_parallel=True, rotate=False, rounded=True, special_characters=False, precision=3)

Export a graphviz dot file representing the learned tree model

Parameters
• out_file (file object or string, optional, default None) – Handle or name of the output file. If None, the result is returned as a string.

• feature_names (list of strings, optional, default None) – Names of each of the features.

• treatment_names (list of strings, optional, default None) – Names of each of the treatments

• max_depth (int or None, optional, default None) – The maximum tree depth to plot

• filled (bool, optional, default False) – When set to True, paint nodes to indicate majority class for classification, extremity of values for regression, or purity of node for multi-output.

• leaves_parallel (bool, optional, default True) – When set to True, draw all leaf nodes at the bottom of the tree.

• rotate (bool, optional, default False) – When set to True, orient tree left to right rather than top-down.

• rounded (bool, optional, default True) – When set to True, draw node boxes with rounded corners and use Helvetica fonts instead of Times-Roman.

• special_characters (bool, optional, default False) – When set to False, ignore special characters for PostScript compatibility.

• precision (int, optional, default 3) – Number of digits of precision for floating point in the values of impurity, threshold and value attributes of each node.

feature_importances(max_depth=4, depth_decay_exponent=2.0)[source]
Parameters
• max_depth (int, default=4) – Splits of depth larger than max_depth are not used in this calculation

• depth_decay_exponent (double, default=2.0) – The contribution of each split to the total score is re-weighted by 1 / (1 + depth)**2.0.

Returns

feature_importances_ – Normalized total parameter heterogeneity inducing importance of each feature

Return type

ndarray of shape (n_features,)

fit(X, y, *, sample_weight=None, check_input=True)[source]

Fit the tree from the data

Parameters
• X ((n, n_features) array) – The features to split on

• y ((n, n_treatments) array) – The reward for each of the m treatments (including baseline treatment)

• sample_weight ((n,) array, default=None) – The sample weights

• check_input (bool, defaul=True) – Whether to check the input parameters for validity. Should be set to False to improve running time in parallel execution, if the variables have already been checked by the forest class that spawned this tree.

Returns

self

Return type

object instance

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_depth – The maximum depth of the tree.

Return type

int

get_n_leaves()

Return the number of leaves of the decision tree.

Returns

self.tree_.n_leaves – Number of leaves.

Return type

int

get_params(deep=True)

Get parameters for this estimator.

Parameters

deep (bool, default=True) – If True, will return the parameters for this estimator and contained subobjects that are estimators.

Returns

params – Parameter names mapped to their values.

Return type

dict

get_train_test_split_inds()

Regenerate the train_test_split of input sample indices that was used for the training and the evaluation split of the honest tree construction structure. Uses the same random seed that was used at fit time and re-generates the indices.

plot(ax=None, title=None, feature_names=None, treatment_names=None, max_depth=None, filled=True, rounded=True, precision=3, fontsize=None)

Exports policy trees to matplotlib

Parameters
• ax (matplotlib.axes.Axes, optional, default None) – The axes on which to plot

• title (string, optional, default None) – A title for the final figure to be printed at the top of the page.

• feature_names (list of strings, optional, default None) – Names of each of the features.

• treatment_names (list of strings, optional, default None) – Names of each of the treatments

• max_depth (int or None, optional, default None) – The maximum tree depth to plot

• filled (bool, optional, default False) – When set to True, paint nodes to indicate majority class for classification, extremity of values for regression, or purity of node for multi-output.

• rounded (bool, optional, default True) – When set to True, draw node boxes with rounded corners and use Helvetica fonts instead of Times-Roman.

• precision (int, optional, default 3) – Number of digits of precision for floating point in the values of impurity, threshold and value attributes of each node.

• fontsize (int, optional, default None) – Font size for text

predict(X, check_input=True)[source]

Predict the best treatment for each sample

Parameters
• X ({array-like} of shape (n_samples, n_features)) – The input samples. Internally, it will be converted to dtype=np.float64.

• check_input (bool, default=True) – Allow to bypass several input checking. Don’t use this parameter unless you know what you do.

Returns

treatment – The recommded treatment, i.e. the treatment index with the largest reward for each sample

Return type

array-like of shape (n_samples)

predict_proba(X, check_input=True)[source]

Predict the probability of recommending each treatment

Parameters
• X ({array-like} of shape (n_samples, n_features)) – The input samples. Internally, it will be converted to dtype=np.float64.

• check_input (bool, default=True) – Allow to bypass several input checking. Don’t use this parameter unless you know what you do.

Returns

treatment_proba – The probability of each treatment recommendation

Return type

array-like of shape (n_samples, n_treatments)

predict_value(X, check_input=True)[source]

Predict the expected value of each treatment for each sample

Parameters
• X ({array-like} of shape (n_samples, n_features)) – The input samples. Internally, it will be converted to dtype=np.float64.

• check_input (bool, default=True) – Allow to bypass several input checking. Don’t use this parameter unless you know what you do.

Returns

welfare – The conditional average welfare for each treatment for the group of each sample defined by the tree

Return type

array-like of shape (n_samples, n_treatments)

render(out_file, format='pdf', view=True, feature_names=None, treatment_names=None, max_depth=None, filled=True, leaves_parallel=True, rotate=False, rounded=True, special_characters=False, precision=3)

Render the tree to a flie

Parameters
• out_file (file name to save to)

• format (string, optional, default ‘pdf’) – The file format to render to; must be supported by graphviz

• view (bool, optional, default True) – Whether to open the rendered result with the default application.

• feature_names (list of strings, optional, default None) – Names of each of the features.

• treatment_names (list of strings, optional, default None) – Names of each of the treatments

• max_depth (int or None, optional, default None) – The maximum tree depth to plot

• filled (bool, optional, default False) – When set to True, paint nodes to indicate majority class for classification, extremity of values for regression, or purity of node for multi-output.

• leaves_parallel (bool, optional, default True) – When set to True, draw all leaf nodes at the bottom of the tree.

• rotate (bool, optional, default False) – When set to True, orient tree left to right rather than top-down.

• rounded (bool, optional, default True) – When set to True, draw node boxes with rounded corners and use Helvetica fonts instead of Times-Roman.

• special_characters (bool, optional, default False) – When set to False, ignore special characters for PostScript compatibility.

• precision (int, optional, default 3) – Number of digits of precision for floating point in the values of impurity, threshold and value attributes of each node.

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

**params (dict) – Estimator parameters.

Returns

self – Estimator instance.

Return type

estimator instance