econml.grf.RegressionForest

class econml.grf.RegressionForest(n_estimators=100, *, max_depth=None, min_samples_split=10, min_samples_leaf=5, min_weight_fraction_leaf=0.0, max_features='auto', min_impurity_decrease=0.0, max_samples=0.45, min_balancedness_tol=0.45, honest=True, inference=True, subforest_size=4, n_jobs=- 1, random_state=None, verbose=0, warm_start=False)[source]

Bases: econml.grf._base_grf.BaseGRF

An implementation of a subsampled honest random forest regressor on top of an sklearn regression tree. Implements subsampling and honesty as described in [rf3], but uses a scikit-learn regression tree as a base. It provides confidence intervals based on ideas described in [rf3] and [rf4]

A random forest is a meta estimator that fits a number of classifying decision trees on various sub-samples of the dataset and uses averaging to improve the predictive accuracy and control over-fitting. The sub-sample size is smaller than the original size and subsampling is performed without replacement. Each decision tree is built in an honest manner: half of the sub-sampled data are used for creating the tree structure (referred to as the splitting sample) and the other half for calculating the constant regression estimate at each leaf of the tree (referred to as the estimation sample). One difference with the algorithm proposed in [rf3] is that we do not ensure balancedness and we do not consider poisson sampling of the features, so that we guarantee that each feature has a positive probability of being selected on each split. Rather we use the original algorithm of Breiman [rf1], which selects the best split among a collection of candidate splits, as long as the max_depth is not reached and as long as there are not more than max_leafs and each child contains at least min_samples_leaf samples and total weight fraction of min_weight_fraction_leaf. Moreover, it allows the use of both mean squared error (MSE) and mean absoulte error (MAE) as the splitting criterion. Finally, we allow for early stopping of the splits if the criterion is not improved by more than min_impurity_decrease. These techniques that date back to the work of [rf1], should lead to finite sample performance improvements, especially for high dimensional features.

The implementation also provides confidence intervals for each prediction using a bootstrap of little bags approach described in [rf3]: subsampling is performed at hierarchical level by first drawing a set of half-samples at random and then sub-sampling from each half-sample to build a forest of forests. All the trees are used for the point prediction and the distribution of predictions returned by each of the sub-forests is used to calculate the standard error of the point prediction.

Parameters
  • n_estimators (int, default 100) – Number of trees

  • 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, {“auto”, “sqrt”, “log2”}, or None, 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.

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

  • max_samples (int or float in (0, 1], default .45,) – The number of samples to use for each subsample that is used to train each tree:

    • If int, then train each tree on max_samples samples, sampled without replacement from all the samples

    • If float, then train each tree on ceil(max_samples * n_samples), sampled without replacement from all the samples.

    If inference=True, then max_samples must either be an integer smaller than n_samples//2 or a float less than or equal to .5.

  • 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 each tree should be trained in an honest manner, i.e. the training set is split into two equal sized subsets, the train and the val set. All samples in train are used to create the split structure and all samples in val are used to calculate the value of each node in the tree.

  • inference (bool, default True) – Whether inference (i.e. confidence interval construction and uncertainty quantification of the estimates) should be enabled. If inference=True, then the estimator uses a bootstrap-of-little-bags approach to calculate the covariance of the parameter vector, with am objective Bayesian debiasing correction to ensure that variance quantities are positive.

  • subforest_size (int, default 4,) – The number of trees in each sub-forest that is used in the bootstrap-of-little-bags calculation. The parameter n_estimators must be divisible by subforest_size. Should typically be a small constant.

  • n_jobs (int or None, default -1) – The number of parallel jobs to be used for parallelism; follows joblib semantics. n_jobs=-1 means all available cpu cores. n_jobs=None means no parallelism.

  • random_state (int, RandomState instance, or None, default None) – Controls the randomness of the estimator. The features are always randomly permuted at each split. 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.

  • verbose (int, default 0) – Controls the verbosity when fitting and predicting.

  • warm_start (bool, default False) – When set to True, reuse the solution of the previous call to fit and add more estimators to the ensemble, otherwise, just fit a whole new forest. If True, then oob_predict method for out-of-bag predictions is not available.

feature_importances_

The feature importances based on the amount of parameter heterogeneity they create. The higher, the more important the feature. The importance of a feature is computed as the (normalized) total heterogeneity that the feature creates. Each split that the feature was chosen adds:

parent_weight * (left_weight * right_weight)
    * mean((value_left[k] - value_right[k])**2) / parent_weight**2

to the importance of the feature. Each such quantity is also weighted by the depth of the split. By default splits below max_depth=4 are not used in this calculation and also each split at depth depth, is re-weighted by 1 / (1 + `depth`)**2.0. See the method feature_importances for a method that allows one to change these defaults.

Type

ndarray of shape (n_features,)

estimators_

The fitted trees.

Type

list of object of type GRFTree

Examples

import numpy as np
from econml.grf import RegressionForest
from sklearn.datasets import make_regression
from sklearn.model_selection import train_test_split

np.set_printoptions(suppress=True)
np.random.seed(123)
X, y = make_regression(n_samples=1000, n_features=4, n_informative=2,
                       random_state=0, shuffle=False)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=.5)
regr = RegressionForest(max_depth=None, random_state=0,
                        n_estimators=1000)
>>> regr.fit(X_train, y_train)
RegressionForest(n_estimators=1000, random_state=0)
>>> regr.feature_importances_
array([0.88..., 0.11..., 0.00..., 0.00...])
>>> regr.predict(np.ones((1, 4)), interval=True, alpha=.05)
(array([[121.0...]]), array([[103.6...]]), array([[138.3...]]))

References

rf1(1,2)
  1. Breiman, “Random Forests”, Machine Learning, 45(1), 5-32, 2001.

rf3(1,2,3,4)

S. Athey, S. Wager, “Estimation and Inference of Heterogeneous Treatment Effects using Random Forests”, Journal of the American Statistical Association 113.523 (2018): 1228-1242.

rf4

S. Athey, J. Tibshirani, and S. Wager, “Generalized random forests”, The Annals of Statistics, 47(2), 1148-1178, 2019.

__init__(n_estimators=100, *, max_depth=None, min_samples_split=10, min_samples_leaf=5, min_weight_fraction_leaf=0.0, max_features='auto', min_impurity_decrease=0.0, max_samples=0.45, min_balancedness_tol=0.45, honest=True, inference=True, subforest_size=4, n_jobs=- 1, random_state=None, verbose=0, warm_start=False)[source]

Methods

__init__([n_estimators, max_depth, ...])

apply(X)

Apply trees in the forest to X, return leaf indices.

decision_path(X)

Return the decision path in the forest.

feature_importances([max_depth, ...])

The feature importances based on the amount of parameter heterogeneity they create. The higher, the more important the feature. The importance of a feature is computed as the (normalized) total heterogeneity that the feature creates. For each tree and for each split that the feature was chosen adds::.

fit(X, y, *[, sample_weight])

Build an IV forest of trees from the training set (X, y).

get_params([deep])

Get parameters for this estimator.

get_subsample_inds()

Re-generate the example same sample indices as those at fit time using same pseudo-randomness.

oob_predict(Xtrain)

Returns the relevant output predictions for each of the training data points, when only trees where that data point was not used are incorporated.

predict(X[, interval, alpha])

Return the prefix of relevant fitted local parameters for each x in X, i.e. theta(x)[1..n_relevant_outputs].

predict_alpha_and_jac(X[, slice, parallel])

Return the value of the conditional jacobian E[J | X=x] and the conditional alpha E[A | X=x] using the forest as kernel weights, i.e..

predict_and_var(X)

Return the prefix of relevant fitted local parameters for each x in X, i.e. theta(x)[1..n_relevant_outputs] and their covariance matrix.

predict_full(X[, interval, alpha])

Return the fitted local parameters for each x in X, i.e. theta(x).

predict_interval(X[, alpha])

Return the confidence interval for the relevant fitted local parameters for each x in X, i.e. theta(x)[1..n_relevant_outputs].

predict_moment_and_var(X, parameter[, ...])

Return the value of the conditional expected moment vector at each sample and for the given parameter estimate for each sample.

predict_projection(X, projector)

Return the inner product of the prefix of relevant fitted local parameters for each x in X, i.e. theta(x)[1..n_relevant_outputs], with a projector vector projector(x), i.e.::.

predict_projection_and_var(X, projector)

Return the inner product of the prefix of relevant fitted local parameters for each x in X, i.e. theta(x)[1..n_relevant_outputs], with a projector vector projector(x), i.e.::.

predict_projection_var(X, projector)

Return the variance of the inner product of the prefix of relevant fitted local parameters for each x in X, i.e. theta(x)[1..n_relevant_outputs], with a projector vector projector(x), i.e.::.

predict_tree_average(X)

Return the prefix of relevant fitted local parameters for each X, i.e. theta(X)[1..n_relevant_outputs].

predict_tree_average_full(X)

Return the fitted local parameters for each X, i.e. theta(X).

predict_var(X)

Return the covariance matrix of the prefix of relevant fitted local parameters for each x in X.

prediction_stderr(X)

Return the standard deviation of each coordinate of the prefix of relevant fitted local parameters for each x in X.

set_params(**params)

Set the parameters of this estimator.

Attributes

feature_importances_

apply(X)

Apply trees in the forest to X, return leaf indices.

Parameters

X (array_like of shape (n_samples, n_features)) – The input samples. Internally, it will be converted to dtype=np.float64.

Returns

X_leaves – For each datapoint x in X and for each tree in the forest, return the index of the leaf x ends up in.

Return type

ndarray of shape (n_samples, n_estimators)

decision_path(X)

Return the decision path in the forest.

Parameters

X (array_like of shape (n_samples, n_features)) – The input samples. Internally, it will be converted to dtype=np.float64.

Returns

  • indicator (sparse matrix of shape (n_samples, n_nodes)) – Return a node indicator matrix where non zero elements indicates that the samples goes through the nodes. The matrix is of CSR format.

  • n_nodes_ptr (ndarray of shape (n_estimators + 1,)) – The columns from indicator[n_nodes_ptr[i]:n_nodes_ptr[i+1]] gives the indicator value for the i-th estimator.

feature_importances(max_depth=4, depth_decay_exponent=2.0)

The feature importances based on the amount of parameter heterogeneity they create. The higher, the more important the feature. The importance of a feature is computed as the (normalized) total heterogeneity that the feature creates. For each tree and for each split that the feature was chosen adds:

parent_weight * (left_weight * right_weight)
    * mean((value_left[k] - value_right[k])**2) / parent_weight**2

to the importance of the feature. Each such quantity is also weighted by the depth of the split. These importances are normalized at the tree level and then averaged across trees.

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)[source]

Build an IV forest of trees from the training set (X, y).

Parameters
  • X (array_like of shape (n_samples, n_features)) – The training input samples. Internally, its dtype will be converted to dtype=np.float64.

  • y (array_like of shape (n_samples,) or (n_samples, n_outcomes)) – The outcome values for each sample.

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

Returns

self

Return type

object

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_subsample_inds()

Re-generate the example same sample indices as those at fit time using same pseudo-randomness.

oob_predict(Xtrain)

Returns the relevant output predictions for each of the training data points, when only trees where that data point was not used are incorporated. This method is not available is the estimator was trained with warm_start=True.

Parameters

Xtrain ((n_training_samples, n_features) matrix) – Must be the same exact X matrix that was passed to the forest at fit time.

Returns

oob_preds – The out-of-bag predictions of the relevant output parameters for each of the training points

Return type

(n_training_samples, n_relevant_outputs) matrix

predict(X, interval=False, alpha=0.05)

Return the prefix of relevant fitted local parameters for each x in X, i.e. theta(x)[1..n_relevant_outputs].

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

  • interval (bool, default False) – Whether to return a confidence interval too

  • alpha (float in (0, 1), default 0.05) – The confidence level of the confidence interval. Returns a symmetric (alpha/2, 1-alpha/2) confidence interval.

Returns

  • theta(X)[1, .., n_relevant_outputs] (array_like of shape (n_samples, n_relevant_outputs)) – The estimated relevant parameters for each row of X

  • lb(x), ub(x) (array_like of shape (n_samples, n_relevant_outputs)) – The lower and upper end of the confidence interval for each parameter. Return value is omitted if interval=False.

predict_alpha_and_jac(X, slice=None, parallel=True)

Return the value of the conditional jacobian E[J | X=x] and the conditional alpha E[A | X=x] using the forest as kernel weights, i.e.:

alpha(x) = (1/n_trees) sum_{trees} (1/ |leaf(x)|) sum_{val sample i in leaf(x)} w[i] A[i]
jac(x) = (1/n_trees) sum_{trees} (1/ |leaf(x)|) sum_{val sample i in leaf(x)} w[i] J[i]

where w[i] is the sample weight (1.0 if sample_weight is None).

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

  • slice (list of int or None, default None) – If not None, then only the trees with index in slice, will be used to calculate the mean and the variance.

  • parallel (bool , default True) – Whether the averaging should happen using parallelism or not. Parallelism adds some overhead but makes it faster with many trees.

Returns

  • alpha (array_like of shape (n_samples, n_outputs)) – The estimated conditional A, alpha(x) for each sample x in X

  • jac (array_like of shape (n_samples, n_outputs, n_outputs)) – The estimated conditional J, jac(x) for each sample x in X

predict_and_var(X)

Return the prefix of relevant fitted local parameters for each x in X, i.e. theta(x)[1..n_relevant_outputs] and their covariance matrix.

Parameters

X (array_like of shape (n_samples, n_features)) – The input samples. Internally, it will be converted to dtype=np.float64.

Returns

  • theta(x)[1, .., n_relevant_outputs] (array_like of shape (n_samples, n_relevant_outputs)) – The estimated relevant parameters for each row of X

  • var(theta(x)) (array_like of shape (n_samples, n_relevant_outputs, n_relevant_outputs)) – The covariance of theta(x)[1, .., n_relevant_outputs]

predict_full(X, interval=False, alpha=0.05)

Return the fitted local parameters for each x in X, i.e. theta(x).

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

  • interval (bool, default False) – Whether to return a confidence interval too

  • alpha (float in (0, 1), default 0.05) – The confidence level of the confidence interval. Returns a symmetric (alpha/2, 1-alpha/2) confidence interval.

Returns

  • theta(x) (array_like of shape (n_samples, n_outputs)) – The estimated relevant parameters for each row x of X

  • lb(x), ub(x) (array_like of shape (n_samples, n_outputs)) – The lower and upper end of the confidence interval for each parameter. Return value is omitted if interval=False.

predict_interval(X, alpha=0.05)

Return the confidence interval for the relevant fitted local parameters for each x in X, i.e. theta(x)[1..n_relevant_outputs].

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

  • alpha (float in (0, 1), default 0.05) – The confidence level of the confidence interval. Returns a symmetric (alpha/2, 1-alpha/2) confidence interval.

Returns

lb(x), ub(x) – The lower and upper end of the confidence interval for each parameter. Return value is omitted if interval=False.

Return type

array_like of shape (n_samples, n_relevant_outputs)

predict_moment_and_var(X, parameter, slice=None, parallel=True)

Return the value of the conditional expected moment vector at each sample and for the given parameter estimate for each sample:

M(x; theta(x)) := E[J | X=x] theta(x) - E[A | X=x]

where conditional expectations are estimated based on the forest weights, i.e.:

M_tree(x; theta(x)) := (1/ |leaf(x)|) sum_{val sample i in leaf(x)} w[i] (J[i] theta(x) - A[i])
M(x; theta(x) = (1/n_trees) sum_{trees} M_tree(x; theta(x))

where w[i] is the sample weight (1.0 if sample_weight is None), as well as the variance of the local moment vector across trees:

Var(M_tree(x; theta(x))) = (1/n_trees) sum_{trees} M_tree(x; theta(x)) @ M_tree(x; theta(x)).T
Parameters
  • X (array_like of shape (n_samples, n_features)) – The input samples. Internally, it will be converted to dtype=np.float64.

  • parameter (array_like of shape (n_samples, n_outputs)) – An estimate of the parameter theta(x) for each sample x in X

  • slice (list of int or None, default None) – If not None, then only the trees with index in slice, will be used to calculate the mean and the variance.

  • parallel (bool , default True) – Whether the averaging should happen using parallelism or not. Parallelism adds some overhead but makes it faster with many trees.

Returns

  • moment (array_like of shape (n_samples, n_outputs)) – The estimated conditional moment M(x; theta(x)) for each sample x in X

  • moment_var (array_like of shape (n_samples, n_outputs)) – The variance of the conditional moment Var(M_tree(x; theta(x))) across trees for each sample x

predict_projection(X, projector)

Return the inner product of the prefix of relevant fitted local parameters for each x in X, i.e. theta(x)[1..n_relevant_outputs], with a projector vector projector(x), i.e.:

mu(x) := <theta(x)[1..n_relevant_outputs], projector(x)>
Parameters
  • X (array_like of shape (n_samples, n_features)) – The input samples. Internally, it will be converted to dtype=np.float64.

  • projector (array_like of shape (n_samples, n_relevant_outputs)) – The projector vector for each sample x in X

Returns

mu(x) – The estimated inner product of the relevant parameters with the projector for each row x of X

Return type

array_like of shape (n_samples, 1)

predict_projection_and_var(X, projector)

Return the inner product of the prefix of relevant fitted local parameters for each x in X, i.e. theta(x)[1..n_relevant_outputs], with a projector vector projector(x), i.e.:

mu(x) := <theta(x)[1..n_relevant_outputs], projector(x)>

as well as the variance of mu(x).

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

  • projector (array_like of shape (n_samples, n_relevant_outputs)) – The projector vector for each sample x in X

Returns

  • mu(x) (array_like of shape (n_samples, 1)) – The estimated inner product of the relevant parameters with the projector for each row x of X

  • var(mu(x)) (array_like of shape (n_samples, 1)) – The variance of the estimated inner product

predict_projection_var(X, projector)

Return the variance of the inner product of the prefix of relevant fitted local parameters for each x in X, i.e. theta(x)[1..n_relevant_outputs], with a projector vector projector(x), i.e.:

Var(mu(x)) for mu(x) := <theta(x)[1..n_relevant_outputs], projector(x)>
Parameters
  • X (array_like of shape (n_samples, n_features)) – The input samples. Internally, it will be converted to dtype=np.float64.

  • projector (array_like of shape (n_samples, n_relevant_outputs)) – The projector vector for each sample x in X

Returns

var(mu(x)) – The variance of the estimated inner product

Return type

array_like of shape (n_samples, 1)

predict_tree_average(X)

Return the prefix of relevant fitted local parameters for each X, i.e. theta(X)[1..n_relevant_outputs]. This method simply returns the average of the parameters estimated by each tree. predict should be preferred over pred_tree_average, as it performs a more stable averaging across trees.

Parameters

X (array_like of shape (n_samples, n_features)) – The input samples. Internally, it will be converted to dtype=np.float64.

Returns

theta(X)[1, .., n_relevant_outputs] – The estimated relevant parameters for each row of X

Return type

array_like of shape (n_samples, n_relevant_outputs)

predict_tree_average_full(X)

Return the fitted local parameters for each X, i.e. theta(X). This method simply returns the average of the parameters estimated by each tree. predict_full should be preferred over pred_tree_average_full, as it performs a more stable averaging across trees.

Parameters

X (array_like of shape (n_samples, n_features)) – The input samples. Internally, it will be converted to dtype=np.float64.

Returns

theta(X) – The estimated relevant parameters for each row of X

Return type

array_like of shape (n_samples, n_outputs)

predict_var(X)

Return the covariance matrix of the prefix of relevant fitted local parameters for each x in X.

Parameters

X (array_like of shape (n_samples, n_features)) – The input samples. Internally, it will be converted to dtype=np.float64.

Returns

var(theta(x)) – The covariance of theta(x)[1, .., n_relevant_outputs]

Return type

array_like of shape (n_samples, n_relevant_outputs, n_relevant_outputs)

prediction_stderr(X)

Return the standard deviation of each coordinate of the prefix of relevant fitted local parameters for each x in X.

Parameters

X (array_like of shape (n_samples, n_features)) – The input samples. Internally, it will be converted to dtype=np.float64.

Returns

std(theta(x)) – The standard deviation of each theta(x)[i] for i in {1, .., n_relevant_outputs}

Return type

array_like of shape (n_samples, n_relevant_outputs)

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