随机森林概率预测与多数投票

机器算法验证 随机森林 Python scikit-学习 聚合 装袋
2022-03-22 16:13:52

Scikit learn似乎使用概率预测而不是多数投票来支持模型聚合技术,而没有解释原因(1.9.2.1. Random Forests)。

为什么有明确的解释?此外,对于可用于随机森林装袋的各种模型聚合技术,是否有一篇好的论文或评论文章?

谢谢!

1个回答

如果您精通 Python,最好通过查看代码来回答此类问题。

RandomForestClassifier.predict,至少在当前版本 0.16.1 中,预测具有最高概率估计的类,由 给出predict_proba这条线

的文档predict_proba说:

输入样本的预测类别概率计算为森林中树木的平均预测类别概率。一棵树的类概率是叶子中同一类的样本的分数。

与原始方法的区别可能只是使得predict预测结果与predict_proba. 结果有时被称为“软投票”,而不是原始 Breiman 论文中使用的“硬”多数票。我无法在快速搜索中找到这两种方法性能的适当比较,但在这种情况下它们似乎都相当合理。

predict文档充其量是具有误导性的;我已经提交了一个拉取请求来修复它。

如果您想改为进行多数投票预测,这里有一个函数可以做到这一点。称它为 likepredict_majvote(clf, X)而不是clf.predict(X). (基于predict_proba; 仅经过轻微测试,但我认为它应该可以工作。)

from scipy.stats import mode
from sklearn.ensemble.forest import _partition_estimators, _parallel_helper
from sklearn.tree._tree import DTYPE
from sklearn.externals.joblib import Parallel, delayed
from sklearn.utils import check_array
from sklearn.utils.validation import check_is_fitted

def predict_majvote(forest, X):
    """Predict class for X.

    Uses majority voting, rather than the soft voting scheme
    used by RandomForestClassifier.predict.

    Parameters
    ----------
    X : array-like or sparse matrix of shape = [n_samples, n_features]
        The input samples. Internally, it will be converted to
        ``dtype=np.float32`` and if a sparse matrix is provided
        to a sparse ``csr_matrix``.
    Returns
    -------
    y : array of shape = [n_samples] or [n_samples, n_outputs]
        The predicted classes.
    """
    check_is_fitted(forest, 'n_outputs_')

    # Check data
    X = check_array(X, dtype=DTYPE, accept_sparse="csr")

    # Assign chunk of trees to jobs
    n_jobs, n_trees, starts = _partition_estimators(forest.n_estimators,
                                                    forest.n_jobs)

    # Parallel loop
    all_preds = Parallel(n_jobs=n_jobs, verbose=forest.verbose,
                         backend="threading")(
        delayed(_parallel_helper)(e, 'predict', X, check_input=False)
        for e in forest.estimators_)

    # Reduce
    modes, counts = mode(all_preds, axis=0)

    if forest.n_outputs_ == 1:
        return forest.classes_.take(modes[0], axis=0)
    else:
        n_samples = all_preds[0].shape[0]
        preds = np.zeros((n_samples, forest.n_outputs_),
                         dtype=forest.classes_.dtype)
        for k in range(forest.n_outputs_):
            preds[:, k] = forest.classes_[k].take(modes[:, k], axis=0)
        return preds

在我尝试的愚蠢合成案例中,预测predict每次都与该方法一致。