scikitgarden的分位数随机森林预测速度非常慢

2024-05-13 21:35:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经开始使用scikit-garden包中的分位数随机森林(QRFs)。以前我使用RandomForestRegressersklearn.ensemble创建常规随机林。在

QRF的速度似乎可以与小数据集大小的常规RF相媲美,但是随着数据量的增加,QRF的预测速度比RF慢得多。在

这是预期的吗?如果是这样的话,有人能解释一下为什么要花这么长的时间才能做出这些预测,并/或就如何更及时地得到分位数预测给出任何建议。在

下面是一个玩具示例,我在这里测试各种数据集大小的训练和预测时间。在

import matplotlib as mpl
mpl.use('Agg')
from sklearn.ensemble import RandomForestRegressor
from skgarden import RandomForestQuantileRegressor
from sklearn.model_selection import train_test_split
import numpy as np
import time
import matplotlib.pyplot as plt

log_ns = np.arange(0.5, 5, 0.5) # number of observations (log10)
ns = (10 ** (log_ns)).astype(int)
print(ns)
m = 14 # number of covariates
train_rf = []
train_qrf = []
pred_rf = []
pred_qrf = []

for n in ns:
    # create dataset
    print('n = {}'.format(n))
    print('m = {}'.format(m))
    rndms = np.random.normal(size=n)
    X = np.random.uniform(size=[n,m])
    betas = np.random.uniform(size=m)
    y = 3 +  np.sum(betas[None,:] * X, axis=1) + rndms

    # split test/train
    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)

    # random forest
    rf = RandomForestRegressor(n_estimators=1000, random_state=0)
    st = time.time()
    rf.fit(X_train, y_train)
    en = time.time()
    print('Fit time RF = {} secs'.format(en - st))
    train_rf.append(en - st)

    # quantile random forest
    qrf = RandomForestQuantileRegressor(random_state=0, min_samples_split=10, n_estimators=1000)
    qrf.set_params(max_features = X.shape[1] // 3)
    st = time.time()
    qrf.fit(X_train, y_train)
    en = time.time()
    print('Fit time QRF = {} secs'.format(en - st))
    train_qrf.append(en - st)


    # predictions
    st = time.time()
    preds_rf = rf.predict(X_test)
    en = time.time()
    print('Prediction time RF = {}'.format(en - st))
    pred_rf.append(en - st)

    st = time.time()
    preds_qrf = qrf.predict(X_test, quantile=50)
    en = time.time()
    print('Prediction time QRF = {}'.format(en - st))
    pred_qrf.append(en - st)

fig, ax = plt.subplots()
ax.plot(np.log10(ns), train_rf, label='RF train', color='blue')
ax.plot(np.log10(ns), train_qrf, label='QRF train', color='red')
ax.plot(np.log10(ns), pred_rf, label='RF predict', color='blue', linestyle=':')
ax.plot(np.log10(ns), pred_qrf, label='QRF predict', color='red', linestyle =':')
ax.legend()
ax.set_xlabel('log(n)')
ax.set_ylabel('time (s)')
fig.savefig('time_comparison.png')

输出如下: Time comparison of RF and QRF training and predictions


Tags: testimporttimenptrainrandomaxen
1条回答
网友
1楼 · 发布于 2024-05-13 21:35:49

我不是这个或任何分位数回归软件包的开发人员,但我看过scikit garden和quantRegForest/ranger的源代码,我对为什么R版本要快得多有了一些想法:

编辑:On a related github issue,lmssdd提到了这种方法如何比论文中的“标准过程”执行得更差。我没有详细阅读这篇文章,所以请带着一点怀疑的态度接受这个答案。

skgarden/quantregforest方法的差异解释

skgarden predict函数的基本思想是保存与所有叶子相对应的所有y_train值。然后,在预测一个新样本时,收集相关的叶和相应的y_train值,并计算该数组的(加权)分位数。R版本采取了一个快捷方式:它们只为每个叶节点保存一个随机选择的y_train值。这有两个好处:它使相关的y_train值的收集变得更简单,因为每个叶节点中始终只有一个值。其次,它使得分位数的计算更加简单,因为每个叶子都有完全相同的权重。在

由于每个叶只使用单个(随机)值,而不是全部使用,因此这是一种近似方法。至少在我的经验中,对50棵树的影响很小。然而,我对数学的了解还不足以说明这个近似值到底有多好。在

如何让skgarden更快地进行预测

下面是一个更简单的分位数预测的R方法的实现,用于一个随机的ForestQuantilerRegressor模型。注意,函数的前半部分是(一次性)选择每个叶的随机y_序列值的过程。如果作者要在skgarden中实现这个方法,他们将逻辑地把这部分移到fit方法,只剩下最后6行左右,这使得{}方法更快。同样在我的例子中,我使用0到1的分位数,而不是从0到100。在

def predict_approx(model, X_test, quantiles=[0.05, 0.5, 0.95]):
    """
    Function to predict quantiles much faster than the default skgarden method
    This is the same method that the ranger and quantRegForest packages in R use
    Output is (n_samples, n_quantiles) or (n_samples, ) if a scalar is given as quantiles
    """
    # Begin one-time calculation of random_values. This only depends on model, so could be saved.
    n_leaves = np.max(model.y_train_leaves_) + 1  # leaves run from 0 to max(leaf_number)
    random_values = np.zeros((model.n_estimators, n_leaves))
    for tree in range(model.n_estimators):
        for leaf in range(n_leaves):
            train_samples = np.argwhere(model.y_train_leaves_[tree, :] == leaf).reshape(-1)
            if len(train_samples) == 0:
                random_values[tree, leaf] = np.nan
            else:
                train_values = model.y_train_[train_samples]
                random_values[tree, leaf] = np.random.choice(train_values)
    # Optionally, save random_values as a model attribute for reuse later

    # For each sample, get the random leaf values from all the leaves they land in
    X_leaves = model.apply(X_test)
    leaf_values = np.zeros((X_test.shape[0], model.n_estimators))
    for i in range(model.n_estimators):
        leaf_values[:, i] = random_values[i, X_leaves[:, i]]

    # For each sample, calculate the quantiles of the leaf_values
    return np.quantile(leaf_values, np.array(quantiles), axis=1).transpose()

相关问题 更多 >