【发布时间】:2013-09-13 05:33:21
【问题描述】:
我正在尝试使用随机森林在 Python 中执行聚类。在随机森林的 R 实现中,您可以设置一个标志来获取邻近矩阵。我似乎在随机森林的 python scikit 版本中找不到任何类似的东西。有谁知道python版本是否有等效计算?
【问题讨论】:
标签: python scikit-learn random-forest
我正在尝试使用随机森林在 Python 中执行聚类。在随机森林的 R 实现中,您可以设置一个标志来获取邻近矩阵。我似乎在随机森林的 python scikit 版本中找不到任何类似的东西。有谁知道python版本是否有等效计算?
【问题讨论】:
标签: python scikit-learn random-forest
我们还没有在 Scikit-Learn 中实现邻近矩阵。
但是,这可以通过依赖我们的决策树实现中提供的apply 函数来完成。也就是说,对于数据集中的所有样本对,遍历森林中的决策树(通过forest.estimators_)并计算它们落在同一片叶子中的次数,即apply 给出的次数对中的两个样本具有相同的节点 ID。
希望这会有所帮助。
【讨论】:
apply 在森林中直接可用,因此您无需自己遍历树。
根据 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. ]])
【讨论】:
目前在 python 中没有为此实现任何东西。我第一次尝试here。如果有人有兴趣将这些方法添加到 scikit 中,那就太好了。
【讨论】: