簡體   English   中英

scikit-learn中R隨機森林特征重要性得分的實現

[英]implementation of R random forest feature importance score in scikit-learn

我正在嘗試為sklearn中的隨機森林回歸模型實現R的特征重要性評分方法; 根據R的文檔:

第一個度量是從排列的OOB數據計算得出的:對於每棵樹,記錄數據自包部分的預測誤差(分類的錯誤率,MSE的回歸率)。 然后,在置換每個預測變量后,將執行相同的操作。 然后,將兩者之間的差異在所有樹上平均,並通過差異的標准偏差進行歸一化。 如果變量的差的標准偏差等於0,則不進行除法運算(但在這種情況下,平均值幾乎始終等於0)。

因此,如果我理解正確,則需要能夠為每棵樹中的OOB樣本置換每個預測變量(特征)。

我了解我可以使用這樣的方法訪問經過訓練的森林中的每棵樹

numberTrees = 100
clf = RandomForestRegressor(n_estimators=numberTrees)
clf.fit(X,Y)
for tree in clf.estimators_:
    do something

無論如何,有沒有獲取每棵樹都是OOB的樣本列表? 也許我可以用每棵樹的random_state來導出OOB樣本列表?

盡管R使用OOB樣本,但我發現通過使用所有訓練樣本,我在scikit中得到了相似的結果。 我正在執行以下操作:

# permute training data and score against its own model  
epoch = 3
seeds = range(epoch)


scores = defaultdict(list) # {feature: change in R^2}

# repeat process several times and then average and then average the score for each feature
for j in xrange(epoch):
    clf = RandomForestRegressor(n_jobs = -1, n_estimators = trees, random_state = seeds[j],
                               max_features = num_features, min_samples_leaf = leaf)

    clf = clf.fit(X_train, y_train)
    acc = clf.score(X_train, y_train)    

    print 'Epoch', j
    # for each feature, permute its values and check the resulting score
    for i, col in enumerate(X_train.columns):
        if i % 200 == 0: print "- feature %s of %s permuted" %(i, X_train.shape[1])
        X_train_copy = X_train.copy()
        X_train_copy[col] = np.random.permutation(X_train[col])
        shuff_acc = clf.score(X_train_copy, y_train)
        scores[col].append((acc-shuff_acc)/acc)

# get mean across epochs
scores_mean = {k: np.mean(v) for k, v in scores.iteritems()}

# sort scores (best first)
scores_sorted = pd.DataFrame.from_dict(scores_mean, orient='index').sort(0, ascending = False)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM