13

我正在尝试使用随机森林在 Python 中执行聚类。在随机森林的 R 实现中,您可以设置一个标志来获取邻近矩阵。我似乎在随机森林的 python scikit 版本中找不到任何类似的东西。有谁知道python版本是否有等效计算?

4

3 回答 3

19

我们还没有在 Scikit-Learn 中实现邻近矩阵。

然而,这可以通过依赖apply我们在决策树实现中提供的函数来完成。也就是说,对于数据集中的所有样本对,遍历森林中的决策树(通过forest.estimators_)并计算它们落在同一叶中的次数,即为apply两个样本提供相同节点 ID的次数在对。

希望这可以帮助。

于 2013-09-10T12:42:32.583 回答
10

基于 Gilles Louppe 的回答,我编写了一个函数。我不知道它是否有效,但它有效。最好的祝福。

def proximityMatrix(model, X, normalize=True):      

    terminals = model.apply(X)
    nTrees = terminals.shape[1]

    a = terminals[:,0]
    proxMat = 1*np.equal.outer(a, a)

    for i in range(1, nTrees):
        a = terminals[:,i]
        proxMat += 1*np.equal.outer(a, a)

    if normalize:
        proxMat = proxMat / nTrees

    return proxMat   

from sklearn.ensemble import  RandomForestClassifier
from sklearn.datasets import load_breast_cancer
train = load_breast_cancer()

model = RandomForestClassifier(n_estimators=500, max_features=2, min_samples_leaf=40)
model.fit(train.data, train.target)
proximityMatrix(model, train.data, normalize=True)
## array([[ 1.   ,  0.414,  0.77 , ...,  0.146,  0.79 ,  0.002],
##        [ 0.414,  1.   ,  0.362, ...,  0.334,  0.296,  0.008],
##        [ 0.77 ,  0.362,  1.   , ...,  0.218,  0.856,  0.   ],
##        ..., 
##        [ 0.146,  0.334,  0.218, ...,  1.   ,  0.21 ,  0.028],
##        [ 0.79 ,  0.296,  0.856, ...,  0.21 ,  1.   ,  0.   ],
##        [ 0.002,  0.008,  0.   , ...,  0.028,  0.   ,  1.   ]])
于 2017-12-20T14:10:54.463 回答
0

目前在python中没有为此实现任何东西。我在这里做了第一次尝试。如果有人有兴趣将这些方法添加到 scikit,那就太好了。

于 2017-04-25T21:23:54.420 回答