WtL*_*Lgi 12 python random-forest scikit-learn
我正在尝试使用随机森林在Python中执行聚类.在随机森林的R实现中,您可以设置一个标记来获取邻近矩阵.我似乎无法在随机森林的python scikit版本中找到类似的东西.有谁知道python版本是否有相同的计算?
Gil*_*ppe 17
我们没有在Scikit-Learn(尚未)中实现邻近矩阵.
但是,这可以通过依赖apply我们的决策树实现中提供的功能来完成.也就是说,对于数据集中的所有样本对,迭代森林中的决策树(直通forest.estimators_)并计算它们落入同一叶子的次数,即,apply为两个样本提供相同节点ID 的次数在一对.
希望这可以帮助.
根据 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. ]])
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3817 次 |
| 最近记录: |