Skip to content

Random forest

smac.model.random_forest.random_forest #

EPMRandomForest #

EPMRandomForest(
    n_estimators: int = 100,
    *,
    log_y: bool = False,
    cross_trees_variance: bool = False,
    criterion: str = "squared_error",
    splitter: str = "random",
    max_depth: int | None = None,
    min_samples_split: int = 2,
    min_samples_leaf: int = 1,
    min_weight_fraction_leaf: float = 0.0,
    max_features: float = 1.0,
    max_leaf_nodes: int | None = None,
    min_impurity_decrease: float = 0.0,
    bootstrap: bool = False,
    oob_score: bool = False,
    n_jobs: int | None = None,
    random_state: int | None = None,
    verbose: int = 0,
    warm_start: bool = False,
    ccp_alpha: float = 0.0,
    max_samples: int | float | None = None,
    monotonic_cst: Iterable | None = None
)

Bases: ForestRegressor

Read more in the :ref:User Guide <tree>.

PARAMETER DESCRIPTION
n_estimators

The number of trees in the forest.

.. versionchanged:: 0.22 The default value of n_estimators changed from 10 to 100 in 0.22.

TYPE: int DEFAULT: 100

criterion

The function to measure the quality of a split. Supported criteria are "squared_error" for the mean squared error, which is equal to variance reduction as feature selection criterion and minimizes the L2 loss using the mean of each terminal node, "friedman_mse", which uses mean squared error with Friedman's improvement score for potential splits, "absolute_error" for the mean absolute error, which minimizes the L1 loss using the median of each terminal node, and "poisson" which uses reduction in Poisson deviance to find splits. Training using "absolute_error" is significantly slower than when using "squared_error".

.. versionadded:: 0.18 Mean Absolute Error (MAE) criterion.

.. versionadded:: 1.0 Poisson criterion.

TYPE: ('squared_error', 'absolute_error', 'friedman_mse', 'poisson') DEFAULT: "squared_error"

max_depth

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.

TYPE: int DEFAULT: None

min_samples_split

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.

.. versionchanged:: 0.18 Added float values for fractions.

TYPE: int or float DEFAULT: 2

min_samples_leaf

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.

.. versionchanged:: 0.18 Added float values for fractions.

TYPE: int or float DEFAULT: 1

min_weight_fraction_leaf

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.

TYPE: float DEFAULT: 0.0

max_features

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 max(1, int(max_features * n_features_in_)) 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 or 1.0, then max_features=n_features.

.. note:: The default of 1.0 is equivalent to bagged trees and more randomness can be achieved by setting smaller values, e.g. 0.3.

.. versionchanged:: 1.1 The default of max_features changed from "auto" to 1.0.

.. deprecated:: 1.1 The "auto" option was deprecated in 1.1 and will be removed in 1.3.

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.

TYPE: ('sqrt', 'log2', None) DEFAULT: "sqrt"

max_leaf_nodes

Grow trees with max_leaf_nodes in best-first fashion. Best nodes are defined as relative reduction in impurity. If None then unlimited number of leaf nodes.

TYPE: int DEFAULT: None

min_impurity_decrease

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.

.. versionadded:: 0.19

TYPE: float DEFAULT: 0.0

bootstrap

Whether bootstrap samples are used when building trees. If False, the whole dataset is used to build each tree.

TYPE: bool DEFAULT: True

oob_score

Whether to use out-of-bag samples to estimate the generalization score. Only available if bootstrap=True.

TYPE: bool DEFAULT: False

n_jobs

The number of jobs to run in parallel. :meth:fit, :meth:predict, :meth:decision_path and :meth:apply are all parallelized over the trees. None means 1 unless in a :obj:joblib.parallel_backend context. -1 means using all processors. See :term:Glossary <n_jobs> for more details.

TYPE: int DEFAULT: None

random_state

Controls both the randomness of the bootstrapping of the samples used when building trees (if bootstrap=True) and the sampling of the features to consider when looking for the best split at each node (if max_features < n_features). See :term:Glossary <random_state> for details.

TYPE: int, RandomState instance or None DEFAULT: None

verbose

Controls the verbosity when fitting and predicting.

TYPE: int DEFAULT: 0

warm_start

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. See :term:Glossary <warm_start> and :ref:gradient_boosting_warm_start for details.

TYPE: bool DEFAULT: False

ccp_alpha

Complexity parameter used for Minimal Cost-Complexity Pruning. The subtree with the largest cost complexity that is smaller than ccp_alpha will be chosen. By default, no pruning is performed. See :ref:minimal_cost_complexity_pruning for details.

.. versionadded:: 0.22

TYPE: non-negative float DEFAULT: 0.0

max_samples

If bootstrap is True, the number of samples to draw from X to train each base estimator.

  • If None (default), then draw X.shape[0] samples.
  • If int, then draw max_samples samples.
  • If float, then draw max_samples * X.shape[0] samples. Thus, max_samples should be in the interval (0.0, 1.0].

.. versionadded:: 0.22

TYPE: int or float DEFAULT: None

criterion

The function to measure the quality of a split. Supported criteria are "squared_error" for the mean squared error, which is equal to variance reduction as feature selection criterion and minimizes the L2 loss using the mean of each terminal node, "friedman_mse", which uses mean squared error with Friedman's improvement score for potential splits, "absolute_error" for the mean absolute error, which minimizes the L1 loss using the median of each terminal node, and "poisson" which uses reduction in Poisson deviance to find splits.

.. versionadded:: 0.18 Mean Absolute Error (MAE) criterion.

.. versionadded:: 0.24 Poisson deviance criterion.

TYPE: ('squared_error', 'friedman_mse', 'absolute_error', 'poisson') DEFAULT: "squared_error"

splitter

The strategy used to choose the split at each node. Supported strategies are "best" to choose the best split and "random" to choose the best random split.

TYPE: ('best', 'random') DEFAULT: "best"

max_depth

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.

TYPE: int DEFAULT: None

min_samples_split

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.

.. versionchanged:: 0.18 Added float values for fractions.

TYPE: int or float DEFAULT: 2

min_samples_leaf

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.

.. versionchanged:: 0.18 Added float values for fractions.

TYPE: int or float DEFAULT: 1

min_weight_fraction_leaf

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.

TYPE: float DEFAULT: 0.0

max_features

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 max(1, int(max_features * n_features_in_)) 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.

.. deprecated:: 1.1 The "auto" option was deprecated in 1.1 and will be removed in 1.3.

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.

TYPE: (int, float or {'auto', 'sqrt', 'log2'}) DEFAULT: None

random_state

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. See :term:Glossary <random_state> for details.

TYPE: int, RandomState instance or None DEFAULT: None

max_leaf_nodes

Grow a tree with max_leaf_nodes in best-first fashion. Best nodes are defined as relative reduction in impurity. If None then unlimited number of leaf nodes.

TYPE: int DEFAULT: None

min_impurity_decrease

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.

.. versionadded:: 0.19

TYPE: float DEFAULT: 0.0

ccp_alpha

Complexity parameter used for Minimal Cost-Complexity Pruning. The subtree with the largest cost complexity that is smaller than ccp_alpha will be chosen. By default, no pruning is performed. See :ref:minimal_cost_complexity_pruning for details.

.. versionadded:: 0.22

TYPE: non-negative float DEFAULT: 0.0

Source code in smac/model/random_forest/random_forest.py
def __init__(
    self,
    n_estimators: int = 100,
    *,
    log_y: bool = False,
    cross_trees_variance: bool = False,
    criterion: str = "squared_error",
    splitter: str = "random",
    max_depth: int | None = None,
    min_samples_split: int = 2,
    min_samples_leaf: int = 1,
    min_weight_fraction_leaf: float = 0.0,
    max_features: float = 1.0,
    max_leaf_nodes: int | None = None,
    min_impurity_decrease: float = 0.0,
    bootstrap: bool = False,
    oob_score: bool = False,
    n_jobs: int | None = None,
    random_state: int | None = None,
    verbose: int = 0,
    warm_start: bool = False,
    ccp_alpha: float = 0.0,
    max_samples: int | float | None = None,
    monotonic_cst: Iterable | None = None,
) -> None:
    """A decision tree regressor.

    Read more in the :ref:`User Guide <tree>`.

    Parameters
    ----------
    n_estimators : int, default=100
        The number of trees in the forest.

        .. versionchanged:: 0.22
            The default value of ``n_estimators`` changed from 10 to 100
            in 0.22.

    criterion : {"squared_error", "absolute_error", "friedman_mse", "poisson"}, \
            default="squared_error"
        The function to measure the quality of a split. Supported criteria
        are "squared_error" for the mean squared error, which is equal to
        variance reduction as feature selection criterion and minimizes the L2
        loss using the mean of each terminal node, "friedman_mse", which uses
        mean squared error with Friedman's improvement score for potential
        splits, "absolute_error" for the mean absolute error, which minimizes
        the L1 loss using the median of each terminal node, and "poisson" which
        uses reduction in Poisson deviance to find splits.
        Training using "absolute_error" is significantly slower
        than when using "squared_error".

        .. versionadded:: 0.18
        Mean Absolute Error (MAE) criterion.

        .. versionadded:: 1.0
        Poisson criterion.

    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=2
        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.

        .. versionchanged:: 0.18
        Added float values for fractions.

    min_samples_leaf : int or float, default=1
        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.

        .. versionchanged:: 0.18
        Added float values for fractions.

    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 : {"sqrt", "log2", None}, int or float, default=1.0
        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
        `max(1, int(max_features * n_features_in_))` 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 or 1.0, then `max_features=n_features`.

        .. note::
            The default of 1.0 is equivalent to bagged trees and more
            randomness can be achieved by setting smaller values, e.g. 0.3.

        .. versionchanged:: 1.1
            The default of `max_features` changed from `"auto"` to 1.0.

        .. deprecated:: 1.1
            The `"auto"` option was deprecated in 1.1 and will be removed
            in 1.3.

        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.

    max_leaf_nodes : int, default=None
        Grow trees with ``max_leaf_nodes`` in best-first fashion.
        Best nodes are defined as relative reduction in impurity.
        If None then unlimited number of leaf nodes.

    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.

        .. versionadded:: 0.19

    bootstrap : bool, default=True
        Whether bootstrap samples are used when building trees. If False, the
        whole dataset is used to build each tree.

    oob_score : bool, default=False
        Whether to use out-of-bag samples to estimate the generalization score.
        Only available if bootstrap=True.

    n_jobs : int, default=None
        The number of jobs to run in parallel. :meth:`fit`, :meth:`predict`,
        :meth:`decision_path` and :meth:`apply` are all parallelized over the
        trees. ``None`` means 1 unless in a :obj:`joblib.parallel_backend`
        context. ``-1`` means using all processors. See :term:`Glossary
        <n_jobs>` for more details.

    random_state : int, RandomState instance or None, default=None
        Controls both the randomness of the bootstrapping of the samples used
        when building trees (if ``bootstrap=True``) and the sampling of the
        features to consider when looking for the best split at each node
        (if ``max_features < n_features``).
        See :term:`Glossary <random_state>` for details.

    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. See :term:`Glossary <warm_start>` and
        :ref:`gradient_boosting_warm_start` for details.

    ccp_alpha : non-negative float, default=0.0
        Complexity parameter used for Minimal Cost-Complexity Pruning. The
        subtree with the largest cost complexity that is smaller than
        ``ccp_alpha`` will be chosen. By default, no pruning is performed. See
        :ref:`minimal_cost_complexity_pruning` for details.

        .. versionadded:: 0.22

    max_samples : int or float, default=None
        If bootstrap is True, the number of samples to draw from X
        to train each base estimator.

        - If None (default), then draw `X.shape[0]` samples.
        - If int, then draw `max_samples` samples.
        - If float, then draw `max_samples * X.shape[0]` samples. Thus,
        `max_samples` should be in the interval `(0.0, 1.0]`.

        .. versionadded:: 0.22

    criterion : {"squared_error", "friedman_mse", "absolute_error", \
            "poisson"}, default="squared_error"
        The function to measure the quality of a split. Supported criteria
        are "squared_error" for the mean squared error, which is equal to
        variance reduction as feature selection criterion and minimizes the L2
        loss using the mean of each terminal node, "friedman_mse", which uses
        mean squared error with Friedman's improvement score for potential
        splits, "absolute_error" for the mean absolute error, which minimizes
        the L1 loss using the median of each terminal node, and "poisson" which
        uses reduction in Poisson deviance to find splits.

        .. versionadded:: 0.18
        Mean Absolute Error (MAE) criterion.

        .. versionadded:: 0.24
            Poisson deviance criterion.

    splitter : {"best", "random"}, default="best"
        The strategy used to choose the split at each node. Supported
        strategies are "best" to choose the best split and "random" to choose
        the best random 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=2
        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.

        .. versionchanged:: 0.18
        Added float values for fractions.

    min_samples_leaf : int or float, default=1
        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.

        .. versionchanged:: 0.18
        Added float values for fractions.

    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
        `max(1, int(max_features * n_features_in_))` 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`.

        .. deprecated:: 1.1
            The `"auto"` option was deprecated in 1.1 and will be removed
            in 1.3.

        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.
        See :term:`Glossary <random_state>` for details.

    max_leaf_nodes : int, default=None
        Grow a tree with ``max_leaf_nodes`` in best-first fashion.
        Best nodes are defined as relative reduction in impurity.
        If None then unlimited number of leaf nodes.

    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.

        .. versionadded:: 0.19

    ccp_alpha : non-negative float, default=0.0
        Complexity parameter used for Minimal Cost-Complexity Pruning. The
        subtree with the largest cost complexity that is smaller than
        ``ccp_alpha`` will be chosen. By default, no pruning is performed. See
        :ref:`minimal_cost_complexity_pruning` for details.

        .. versionadded:: 0.22
    """
    super().__init__(
        DecisionTreeRegressor(),
        n_estimators,
        estimator_params=(
            "criterion",
            "max_depth",
            "min_samples_split",
            "min_samples_leaf",
            "min_weight_fraction_leaf",
            "max_features",
            "max_leaf_nodes",
            "min_impurity_decrease",
            "random_state",
            "ccp_alpha",
            "monotonic_cst",
        ),
        bootstrap=bootstrap,
        oob_score=oob_score,
        n_jobs=n_jobs,
        random_state=random_state,
        verbose=verbose,
        warm_start=warm_start,
        max_samples=max_samples,
    )
    self.criterion = criterion
    self.max_depth = max_depth
    self.min_samples_split = min_samples_split
    self.min_samples_leaf = min_samples_leaf
    self.min_weight_fraction_leaf = min_weight_fraction_leaf
    self.max_features = max_features
    self.max_leaf_nodes = max_leaf_nodes
    self.min_impurity_decrease = min_impurity_decrease
    self.ccp_alpha = ccp_alpha
    self.monotonic_cst = monotonic_cst
    self.splitter = splitter
    self.log_y = log_y
    self.cross_trees_variance = cross_trees_variance

all_trees_pred #

all_trees_pred(X: ndarray) -> ndarray

This function is used to parally predict the target X values. It is based on rf regressor from sklearn 1.6.1: github.com/scikit-learn/scikit-learn/blob/99bf3d8e4eed5ba5db19a1869482a238b6223ffd/sklearn/ensemble/_forest.py#L1045

PARAMETER DESCRIPTION
X

input feature X

TYPE: ndarray

RETURNS DESCRIPTION
preds

Predictions from all trees

TYPE: np.ndarray [#samples, #estimators,#output]

Source code in smac/model/random_forest/random_forest.py
def all_trees_pred(self, X: np.ndarray) -> np.ndarray:
    """
    This function is used to parally predict the target X values. It is based on rf regressor from sklearn 1.6.1:
    https://github.com/scikit-learn/scikit-learn/blob/99bf3d8e4eed5ba5db19a1869482a238b6223ffd/sklearn/ensemble/_forest.py#L1045

    Parameters
    ----------
    X: np.ndarray [#samples, #features]
        input feature X

    Returns
    -------
    preds: np.ndarray [#samples, #estimators,#output]
        Predictions from all trees

    """
    # check_is_fitted(self)
    # Check data
    X = self._validate_X_predict(X)

    if X.ndim == 1:
        X = X[None, :]

    # Assign chunk of trees to jobs
    n_jobs, _, _ = _partition_estimators(self.n_estimators, self.n_jobs)

    # avoid storing the output of every estimator by summing them here
    if self.n_outputs_ > 1:
        preds = np.zeros((X.shape[0], self.n_estimators, self.n_outputs_), dtype=np.float64)
    else:
        preds = np.zeros((X.shape[0], self.n_estimators), dtype=np.float64)

    # Parallel loop
    Parallel(n_jobs=n_jobs, verbose=self.verbose, require="sharedmem")(
        delayed(estimator_predict)(e.predict, X, preds, tree_idx) for tree_idx, e in enumerate(self.estimators_)
    )
    # This should be equivalent to the following implementation

    # preds_ = np.zeros([len(X), self.n_estimators])
    # for i, tree in enumerate(self.estimators_):
    #    preds_[:, i] = tree.predict(X)
    # assert np.allclose(preds, preds_)

    return preds

fit #

fit(X: ndarray, y: ndarray, sample_weight=None) -> None

Build a forest of trees from the training set (X, y). In additional to the vanilla RF fitting process, we also need to edit the estimators' parameters after the fitting process when self.log_y is True. This ensures that the model performance consistently compared to the pyrfr version. To compute the means of all the values, we first need to recover the log scaled values stored in the leave nodes to their raw scale and then compute the mean over those values. This mean value will then transformed back to the log scale.

PARAMETER DESCRIPTION
X

The training input samples. Internally, its dtype will be converted to dtype=np.float32. If a sparse matrix is provided, it will be converted into a sparse csc_matrix.

TYPE: array-like, sparse matrix DEFAULT: array-like

y

The target values (class labels in classification, real numbers in regression).

TYPE: array-like of shape (n_samples,) or (n_samples, n_outputs)

sample_weight

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. In the case of classification, splits are also ignored if they would result in any single class carrying a negative weight in either child node.

TYPE: array-like of shape (n_samples,) DEFAULT: None

RETURNS DESCRIPTION
self

Fitted estimator.

TYPE: object

Source code in smac/model/random_forest/random_forest.py
def fit(self, X: np.ndarray, y: np.ndarray, sample_weight=None) -> None:  # type: ignore
    """
    Build a forest of trees from the training set (X, y). In additional to the vanilla RF fitting process, we also
    need to edit the estimators' parameters after the fitting process when self.log_y is True. This ensures that the
    model performance consistently compared to the pyrfr version. To compute the means of all the values, we first
    need to recover the log scaled values stored in the leave nodes to their raw scale and then compute the mean
    over those values. This mean value will then transformed back to the log scale.

    Parameters
    ----------
    X : {array-like, sparse matrix} of shape (n_samples, n_features)
        The training input samples. Internally, its dtype will be converted
        to ``dtype=np.float32``. If a sparse matrix is provided, it will be
        converted into a sparse ``csc_matrix``.

    y : array-like of shape (n_samples,) or (n_samples, n_outputs)
        The target values (class labels in classification, real numbers in
        regression).

    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. In the case of
        classification, splits are also ignored if they would result in any
        single class carrying a negative weight in either child node.

    Returns
    -------
    self : object
        Fitted estimator.
    """
    assert sample_weight is None, "Sample weights are not supported"
    super().fit(X=X, y=y, sample_weight=sample_weight)

    self.trainX = X
    self.trainY = y
    if self.log_y:
        for tree, samples_idx in zip(self.estimators_, self.estimators_samples_):
            curX = X[samples_idx]
            curY = y[samples_idx]
            preds = tree.apply(curX)
            for k in np.unique(preds):
                tree.tree_.value[k, 0, 0] = np.log(np.exp(curY[preds == k]).mean())

predict #

predict(X: ndarray) -> Tuple[ndarray, ndarray]

Predict the mean and variance of X. Here mean and variances are the empirical mean and variance values from the prediction results of the other trees.

PARAMETER DESCRIPTION
X

Input data points to be testsed.

TYPE: ndarray

RETURNS DESCRIPTION
means: np.ndarray [#samples, 1]
predicted mean.

vars: np.ndarray [#samples, 1] predicted variance.

Source code in smac/model/random_forest/random_forest.py
def predict(self, X: np.ndarray) -> Tuple[np.ndarray, np.ndarray]:
    """
    Predict the mean and variance of X. Here mean and variances are the empirical mean and variance values from the
    prediction results of the other trees.

    Parameters
    ----------
    X: np.ndarray [#samples, #hyperparameter]
        Input data points to be testsed.

    Returns
    -------
        means: np.ndarray [#samples, 1]
            predicted mean.
        vars: np.ndarray [#samples, 1]
            predicted variance.

    """
    preds = self.all_trees_pred(X)

    means = preds.mean(axis=1)
    vars = preds.var(axis=1)

    return means.reshape(-1, 1), vars.reshape(-1, 1)

predict_marginalized_over_instances_batch #

predict_marginalized_over_instances_batch(
    X: ndarray, X_feat: ndarray, log_y: bool
) -> ndarray

Collects the predictions for each tree in the forest for multiple configurations over a set of instances. Each configuration vector is combined with all the instance feature vectors. Based on the response values over all these feature vectors the mean is computed. In the case of log transformation the response values are decompressed before averaging.

PARAMETER DESCRIPTION
X

Input data points.

TYPE: ndarray

X_feat

Features (np.ndarray) of the instances (str). The features are incorporated into the X data, on which the model is trained on.

TYPE: ndarray

log_y

if log_y is applied to the predictions.

TYPE: bool

RETURNS DESCRIPTION
preds

predictions for each sample and trees. Each element in preds corresponds to the mean response values for the target estimator and configuration accross all the instances.

TYPE: np.ndarray [#samples, #estimators]

Source code in smac/model/random_forest/random_forest.py
def predict_marginalized_over_instances_batch(self, X: np.ndarray, X_feat: np.ndarray, log_y: bool) -> np.ndarray:
    """
    Collects the predictions for each tree in the forest for multiple configurations over a set of instances.
    Each configuration vector is combined with all the instance feature vectors. Based on the response values over
    all these feature vectors the mean is computed. In the case of log transformation the response values are
    decompressed before averaging.

    Parameters
    ----------
    X: np.ndarray [#samples, #hyperparameter]
        Input data points.
    X_feat: np.ndarray [#instance, #features],
        Features (np.ndarray) of the instances (str). The features are incorporated into the X data,
        on which the model is trained on.
    log_y: bool,
        if log_y is applied to the predictions.

    Returns
    -------
    preds: np.ndarray [#samples, #estimators]
        predictions for each sample and trees. Each element in preds corresponds to the mean response values for
        the target estimator and configuration accross all the instances.

    """
    X = self._validate_X_predict(X, ensure_2d=False)
    X_feat = self._validate_X_predict(X_feat, ensure_2d=False)
    assert X.shape[-1] + X_feat.shape[-1] == self.n_features_in_

    n_instances = len(X_feat)

    if X.ndim == 1:
        X = X[None, :]

    # Assign chunk of trees to jobs
    n_jobs, _, _ = _partition_estimators(self.n_estimators * n_instances, self.n_jobs)

    # avoid storing the output of every estimator by summing them here
    if self.n_outputs_ > 1:
        preds = np.zeros((X.shape[0], self.n_estimators, self.n_outputs_), dtype=np.float64)
    else:
        preds = np.zeros((X.shape[0], self.n_estimators), dtype=np.float64)
    lock = threading.Lock()
    # Parallel loop
    Parallel(n_jobs=n_jobs, verbose=self.verbose, require="sharedmem")(
        delayed(accumulate_predict_over_instances)(e.predict, X, x_feat, preds, tree_idx, n_instances, lock)
        for (tree_idx, e), x_feat in product(enumerate(self.estimators_), X_feat)
    )

    return preds

RandomForest #

RandomForest(
    configspace: ConfigurationSpace,
    max_samples: int | float | None = None,
    ratio_features: float = 5.0 / 6.0,
    log_y: bool = False,
    instance_features: (
        dict[str, list[int | float]] | None
    ) = None,
    pca_components: int | None = 7,
    seed: int = 0,
    n_trees: int = N_TREES,
    cross_trees_variance: bool = False,
    criterion: str = "squared_error",
    splitter: str = "random",
    max_depth: int = 2**20,
    min_samples_split: int = 3,
    min_samples_leaf: int = 3,
    min_weight_fraction_leaf: float = 0.0,
    max_leaf_nodes: int = 2**20,
    min_impurity_decrease: float = 1e-08,
    bootstrapping: bool = True,
    oob_score: bool = False,
    n_jobs: int | None = -1,
    verbose: int = 0,
    warm_start: bool = False,
    ccp_alpha: float = 0.0,
    monotonic_cst: Iterable | None = None,
)

Bases: AbstractRandomForest

Random forest that takes instance features into account.

PARAMETER DESCRIPTION
n_trees

The number of trees in the random forest.

TYPE: int, defaults to `N_TREES` DEFAULT: N_TREES

max_samples

Number of points per tree. If the value is None, the number of samples will be used. Otherwise, use max_samples (if it is int) or max(round(n_samples * max_samples), 1) (if it is float value)

TYPE: int | float | None, defaults to None DEFAULT: None

ratio_features

The ratio of features that are considered for splitting.

TYPE: float, defaults to 5.0 / 6.0 DEFAULT: 5.0 / 6.0

min_samples_split

The minimum number of data points to perform a split.

TYPE: int, defaults to 3 DEFAULT: 3

min_samples_leaf

The minimum number of data points in a leaf.

TYPE: int, defaults to 3 DEFAULT: 3

max_depth

The maximum depth of a single tree.

TYPE: int, defaults to 2**20 DEFAULT: 2 ** 20

max_leaf_nodes

The maximum total number of nodes in a tree.

TYPE: int, defaults to 2**20 DEFAULT: 2 ** 20

bootstrapping

Enables bootstrapping.

TYPE: bool, defaults to True DEFAULT: True

log_y

The y values (passed to this random forest) are expected to be log(y) transformed. This will be considered during predicting.

TYPE: bool DEFAULT: False

instance_features

Features (list of int or floats) of the instances (str). The features are incorporated into the X data, on which the model is trained on.

TYPE: dict[str, list[int | float]] | None, defaults to None DEFAULT: None

pca_components

Number of components to keep when using PCA to reduce dimensionality of instance features.

TYPE: float, defaults to 7 DEFAULT: 7

seed

TYPE: int DEFAULT: 0

Source code in smac/model/random_forest/random_forest.py
def __init__(
    self,
    configspace: ConfigurationSpace,
    max_samples: int | float | None = None,
    ratio_features: float = 5.0 / 6.0,
    log_y: bool = False,
    instance_features: dict[str, list[int | float]] | None = None,
    pca_components: int | None = 7,
    seed: int = 0,
    n_trees: int = N_TREES,
    cross_trees_variance: bool = False,
    criterion: str = "squared_error",
    splitter: str = "random",
    max_depth: int = 2**20,
    min_samples_split: int = 3,
    min_samples_leaf: int = 3,
    min_weight_fraction_leaf: float = 0.0,
    max_leaf_nodes: int = 2**20,
    min_impurity_decrease: float = 1e-8,
    bootstrapping: bool = True,
    oob_score: bool = False,
    n_jobs: int | None = -1,
    verbose: int = 0,
    warm_start: bool = False,
    ccp_alpha: float = 0.0,
    monotonic_cst: Iterable | None = None,
) -> None:
    super().__init__(
        configspace=configspace,
        instance_features=instance_features,
        pca_components=pca_components,
        seed=seed,
    )

    max_features = 0 if ratio_features > 1.0 else max(1, int(len(self._types) * ratio_features))

    self._rf: EPMRandomForest | None = None
    self._rng = np.random.default_rng(seed=seed)  # type: ignore

    self._log_y = log_y

    self._rf_opts = {
        "n_estimators": n_trees,
        "cross_trees_variance": cross_trees_variance,
        "criterion": criterion,
        "splitter": splitter,
        "max_depth": max_depth,
        "min_samples_split": min_samples_split,
        "min_samples_leaf": min_samples_leaf,
        "min_weight_fraction_leaf": min_weight_fraction_leaf,
        "max_leaf_nodes": max_leaf_nodes,
        "min_impurity_decrease": min_impurity_decrease,
        "bootstrap": bootstrapping,
        "oob_score": oob_score,
        "n_jobs": n_jobs,
        "verbose": verbose,
        "warm_start": warm_start,
        "ccp_alpha": ccp_alpha,
        "max_samples": max_samples,
        "monotonic_cst": monotonic_cst,
        "random_state": seed,
        "max_features": max_features,
        "log_y": log_y,
    }

predict #

predict(
    X: ndarray, covariance_type: str | None = "diagonal"
) -> tuple[ndarray, ndarray | None]

Predicts mean and variance for a given X. Internally, calls the method _predict.

PARAMETER DESCRIPTION
X

Input data points.

TYPE: np.ndarray [#samples, #hyperparameters + #features]

covariance_type

Specifies what to return along with the mean. Applied only to Gaussian Processes. Takes four valid inputs: * None: Only the mean is returned. * "std": Standard deviation at test points is returned. * "diagonal": Diagonal of the covariance matrix is returned. * "full": Whole covariance matrix between the test points is returned.

TYPE: str | None DEFAULT: 'diagonal'

RETURNS DESCRIPTION
means

The predictive mean.

TYPE: np.ndarray [#samples, #objectives]

vars

Predictive variance or standard deviation.

TYPE: np.ndarray [#samples, #objectives] or [#samples, #samples] | None

Source code in smac/model/abstract_model.py
def predict(
    self,
    X: np.ndarray,
    covariance_type: str | None = "diagonal",
) -> tuple[np.ndarray, np.ndarray | None]:
    """Predicts mean and variance for a given X. Internally, calls the method `_predict`.

    Parameters
    ----------
    X : np.ndarray [#samples, #hyperparameters + #features]
        Input data points.
    covariance_type: str | None, defaults to "diagonal"
        Specifies what to return along with the mean. Applied only to Gaussian Processes.
        Takes four valid inputs:
        * None: Only the mean is returned.
        * "std": Standard deviation at test points is returned.
        * "diagonal": Diagonal of the covariance matrix is returned.
        * "full": Whole covariance matrix between the test points is returned.

    Returns
    -------
    means : np.ndarray [#samples, #objectives]
        The predictive mean.
    vars : np.ndarray [#samples, #objectives] or [#samples, #samples] | None
        Predictive variance or standard deviation.
    """
    if len(X.shape) != 2:
        raise ValueError("Expected 2d array, got %dd array!" % len(X.shape))

    if X.shape[1] != self._n_hps + self._n_features:
        raise ValueError(
            f"Feature mismatch: X should have {self._n_hps} hyperparameters + {self._n_features} features, "
            f"but has {X.shape[1]} in total."
        )

    if self._apply_pca:
        try:
            X_feats = X[:, -self._n_features :]
            X_feats = self._scaler.transform(X_feats)
            X_feats = self._pca.transform(X_feats)
            X = np.hstack((X[:, : self._n_hps], X_feats))
        except NotFittedError:
            # PCA not fitted if only one training sample
            pass

    if X.shape[1] != len(self._types):
        raise ValueError("Rows in X should have %d entries but have %d!" % (len(self._types), X.shape[1]))

    with warnings.catch_warnings():
        warnings.filterwarnings("ignore", "Predicted variances smaller than 0. Setting those variances to 0.")
        mean, var = self._predict(X, covariance_type)

    if len(mean.shape) == 1:
        mean = mean.reshape((-1, 1))

    if var is not None and len(var.shape) == 1:
        var = var.reshape((-1, 1))

    return mean, var

predict_marginalized #

predict_marginalized(X: ndarray) -> tuple[ndarray, ndarray]

Predicts mean and variance marginalized over all instances.

Under the hood: Collects the predictions for each tree in the forest for multiple configurations over a set of instances. Each configuration vector is combined with all the instance feature vectors. Based on the response values over all these feature vectors the mean is computed. In the case of log transformation the response values are decompressed before averaging.

Note

The method is random forest specific and follows the SMAC2 implementation. It requires no distribution assumption to marginalize the uncertainty estimates.

PARAMETER DESCRIPTION
X

Input data points.

TYPE: np.ndarray [#samples, #hyperparameter + #features]

RETURNS DESCRIPTION
means

The predictive mean.

TYPE: np.ndarray [#samples, 1]

vars

The predictive variance.

TYPE: np.ndarray [#samples, 1]

Source code in smac/model/random_forest/random_forest.py
def predict_marginalized(self, X: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
    """Predicts mean and variance marginalized over all instances.

    Under the hood: Collects the predictions for each tree in the forest
    for multiple configurations over a set of instances. Each configuration
    vector is combined with all the instance feature vectors. Based on the
    response values over all these feature vectors the mean is computed.
    In the case of log transformation the response values are decompressed
    before averaging.

    Note
    ----
    The method is random forest specific and follows the SMAC2 implementation. It requires
    no distribution assumption to marginalize the uncertainty estimates.

    Parameters
    ----------
    X : np.ndarray [#samples, #hyperparameter + #features]
        Input data points.

    Returns
    -------
    means : np.ndarray [#samples, 1]
        The predictive mean.
    vars : np.ndarray [#samples, 1]
        The predictive variance.
    """
    if self._n_features == 0:
        mean_, var = self.predict(X)
        assert var is not None

        var[var < self._var_threshold] = self._var_threshold
        var[np.isnan(var)] = self._var_threshold

        return mean_, var

    assert self._instance_features is not None

    if len(X.shape) != 2:
        raise ValueError("Expected 2d array, got %dd array!" % len(X.shape))

    if X.shape[1] != len(self._bounds):
        raise ValueError("Rows in X should have %d entries but have %d!" % (len(self._bounds), X.shape[1]))

    assert self._rf is not None
    X = self._impute_inactive(X)

    X_feat = np.asarray(list(self._instance_features.values()))
    dat_ = self._rf.predict_marginalized_over_instances_batch(X, X_feat, self._log_y)
    dat_ = np.array(dat_)

    # 3. compute statistics across trees
    mean_ = dat_.mean(axis=1)
    var = dat_.var(axis=1)

    if var is None:
        raise RuntimeError("The variance must not be none.")

    var[var < self._var_threshold] = self._var_threshold

    if len(mean_.shape) == 1:
        mean_ = mean_.reshape((-1, 1))
    if len(var.shape) == 1:
        var = var.reshape((-1, 1))

    return mean_, var

train #

train(X: ndarray, Y: ndarray) -> Self

Trains the random forest on X and Y. Internally, calls the method _train.

PARAMETER DESCRIPTION
X

Input data points.

TYPE: np.ndarray [#samples, #hyperparameters + #features]

Y

The corresponding target values.

TYPE: np.ndarray [#samples, #objectives]

RETURNS DESCRIPTION
self

TYPE: AbstractModel

Source code in smac/model/abstract_model.py
def train(self: Self, X: np.ndarray, Y: np.ndarray) -> Self:
    """Trains the random forest on X and Y. Internally, calls the method `_train`.

    Parameters
    ----------
    X : np.ndarray [#samples, #hyperparameters + #features]
        Input data points.
    Y : np.ndarray [#samples, #objectives]
        The corresponding target values.

    Returns
    -------
    self : AbstractModel
    """
    if len(X.shape) != 2:
        raise ValueError("Expected 2d array, got %dd array!" % len(X.shape))

    if X.shape[1] != self._n_hps + self._n_features:
        raise ValueError(
            f"Feature mismatch: X should have {self._n_hps} hyperparameters + {self._n_features} features, "
            f"but has {X.shape[1]} in total."
        )

    if X.shape[0] != Y.shape[0]:
        raise ValueError("X.shape[0] ({}) != y.shape[0] ({})".format(X.shape[0], Y.shape[0]))

    # Reduce dimensionality of features if larger than PCA_DIM
    if (
        self._pca_components is not None
        and X.shape[0] > self._pca.n_components
        and self._n_features >= self._pca_components
    ):
        X_feats = X[:, -self._n_features :]

        # Scale features
        X_feats = self._scaler.fit_transform(X_feats)
        X_feats = np.nan_to_num(X_feats)  # if features with max == min

        # PCA
        X_feats = self._pca.fit_transform(X_feats)
        X = np.hstack((X[:, : self._n_hps], X_feats))

        if hasattr(self, "_types"):
            # For RF, adapt types list
            # if X_feats.shape[0] < self._pca, X_feats.shape[1] == X_feats.shape[0]
            self._types = np.array(
                np.hstack((self._types[: self._n_hps], np.zeros(X_feats.shape[1]))),
                dtype=np.uint,
            )  # type: ignore

        self._apply_pca = True
    else:
        self._apply_pca = False

        if hasattr(self, "_types"):
            self._types = copy.deepcopy(self._initial_types)

    return self._train(X, Y)

accumulate_predict_over_instances #

accumulate_predict_over_instances(
    predict: Callable,
    X: ndarray,
    X_instance_feat: ndarray,
    results: ndarray,
    tree_idx: int,
    n_instances: int,
    lock: Lock,
) -> None

Collect predictions from a single estimator. However, we sum the results from all instances

PARAMETER DESCRIPTION
predict

the prediction function, in this scenario, it is the prediction function of each tree

TYPE: Callable

X

Input data points.

TYPE: ndarray

X_instance_feat

Features (np.ndarray) of the instances (str). The features are incorporated into the X data, on which the model is trained on.

TYPE: ndarray

results

output values from all the predictors

TYPE: ndarray

tree_idx

tree index

TYPE: int

n_instances

number of instance

TYPE: int

lock

threading lock

TYPE: Lock

Source code in smac/model/random_forest/random_forest.py
def accumulate_predict_over_instances(
    predict: Callable,
    X: np.ndarray,
    X_instance_feat: np.ndarray,
    results: np.ndarray,
    tree_idx: int,
    n_instances: int,
    lock: threading.Lock,
) -> None:
    """
    Collect predictions from a single estimator. However, we sum the results from all instances

    Parameters
    ----------
    predict: Callable
        the prediction function, in this scenario, it is the prediction function of each tree
    X: np.ndarray [#samples, #hyperparameter]
        Input data points.
    X_instance_feat: np.ndarray [#instance, #features],
        Features (np.ndarray) of the instances (str). The features are incorporated into the X data,
         on which the model is trained on.

    results: np.ndarray [#samples, #estimators]
        output values from all the predictors
    tree_idx: int
        tree index
    n_instances: int
        number of instance
    lock: threading.Lock
        threading lock
    """
    X_instance_feat_ = np.tile(X_instance_feat[None, :], (len(X), 1))
    prediction = predict(np.concatenate([X, X_instance_feat_], axis=1), check_input=False)
    with lock:
        results[:, tree_idx,] += (
            prediction / n_instances
        )

estimator_predict #

estimator_predict(
    predict: Callable,
    X: ndarray,
    results: ndarray,
    tree_idx: int,
) -> None

Collect predictions from a single estimator.

PARAMETER DESCRIPTION
predict

the prediction function, in this scenario, it is the prediction function of each tree

TYPE: Callable

X

input features

TYPE: ndarray

results

output values from all the predictors

TYPE: ndarray

tree_idx

estimator index

TYPE: int

Source code in smac/model/random_forest/random_forest.py
def estimator_predict(predict: Callable, X: np.ndarray, results: np.ndarray, tree_idx: int) -> None:
    """
    Collect predictions from a single estimator.

    Parameters
    ----------
    predict: Callable
        the prediction function, in this scenario, it is the prediction function of each tree
    X: np.ndarray [#samples, #hyperparameter]
        input features
    results: np.ndarray [#samples, #estimators]
        output values from all the predictors
    tree_idx:
        estimator index
    """
    prediction = predict(X, check_input=False)
    results[:, tree_idx] = prediction  # Populate the corresponding column